原生nodejs文件上传后,通过链接访问图片

原生nodejs文件上传:原生nodejs上传文件 不使用框架-CSDN博客

示例代码:

const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');

// 设置公开目录
const publicDir = path.join(__dirname, 'public');
const uploadDir = path.join(publicDir, 'uploads');

// 检查并创建 uploads 文件夹
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
    console.log('Uploads directory created.');
}

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    // 提供静态文件服务
    if (req.method === 'GET' && parsedUrl.pathname.startsWith('/uploads')) {
        const filePath = path.join(uploadDir, parsedUrl.pathname.replace('/uploads/', ''));
        fs.readFile(filePath, (err, data) => {
            if (err) {
                res.writeHead(404, { 'Content-Type': 'text/plain' });
                res.end('File not found');
                return;
            }

            // 根据文件类型设置 Content-Type
            const ext = path.extname(filePath).toLowerCase();
            const mimeTypes = {
                '.jpg': 'image/jpeg',
                '.jpeg': 'image/jpeg',
                '.png': 'image/png',
                '.gif': 'image/gif'
            };
            const contentType = mimeTypes[ext] || 'application/octet-stream';

            res.writeHead(200, { 'Content-Type': contentType });
            res.end(data);
        });
    }
    // 其他请求
    else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});


server.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});