繁体   English   中英

如何使用http模块作为文件提供图片?

[英]How to serve image with http module as a file?

我建立了一个服务器来处理某种类型的请求(html和图像文件)。
使用浏览器请求文件时,可以查看html文件或请求的图像。

我也尝试过建立一个客户端脚本来请求文件。 当我请求html文件时,我可以正确接收它。
但是,当我请求图像文件时,它已被接收,但是我无法查看图像。

如何接收图像作为文件?

服务器的相关路径:

const server = http.createServer((req, res) => {
    console.log(`${req.method} request for ${req.url}`);
    console.log(`From: ${req.connection.remoteAddress}`);
    let fileName = req.url;
    if (utils.isFileExistsInDirectory(__dirname, fileName)) {
        if (_.includes(fileName, '.html')) {
            fs.readFile(`${__dirname}/${fileName}`, (err, data) => {
                if (err) {
                    res.writeHead(400, {'Content-type':'text/html'});
                    res.end('A trouble occurred with the file.');
                } else {
                    res.writeHead(200, {'Content-Type': 'text/html'});
                    res.end(data);
                }
            });
        } else if (fileName.match(/.png$/)) {
            fs.readFile(path.join(__dirname, 'images', fileName), (err, data) => {
                if (err) {
                    res.writeHead(400, {'Content-type':'text/html'});
                    res.end('A trouble occurred with the file.');
                } else {
                    res.writeHead(200, {'Content-Type': 'image/png'});
                    res.end(data);
                }
            });
        } else {
            fs.readFile(`${__dirname}/${fileName}`, (err, data) => {
                if (err) {
                    res.writeHead(400, {'Content-type':'text/html'});
                    res.end('A trouble occurred with the file.');
                } else {
                    res.writeHead(200, {'Content-Type': 'text/plain'});
                    res.end(data);
                }
            });
        }
    } else {
        res.writeHead(404, {'Content-type':'text/html'});
        res.end('File not found.');
    }
});

客户相关部分:

const req = http.request(options, res => {
    let responseBody = '';
    res.on('data', chunk => {
        responseBody += chunk;
    });
    res.on('end', () => {
        if (!fs.existsSync(`${__dirname}/${dir}`)){
            fs.mkdirSync(`${__dirname}/${dir}`);
        }
        fs.writeFile(`${__dirname}/${dir}/${path}`, responseBody, err => {
            if (err) {
                throw err;
            }
        });
    });
});
req.on('error', err => {
    console.log(`problem with request: ${err}`);
});
req.end();

尝试将图像编码为base64字符串

    my.get("/getimg", function(req, res)
    {
        var img = new Buffer(data, 'base64');

        res.writeHead(200, {
            'Content-Type': 'image/png',
            'Content-Length': img.length
        });
        res.end(img); 
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM