简体   繁体   English

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

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

I've built a server which handles some type of requests (html and image files). 我建立了一个服务器来处理某种类型的请求(html和图像文件)。
When I'm requesting the files with the browser, I'm able to view the html file or the requested image. 使用浏览器请求文件时,可以查看html文件或请求的图像。

I've tried also to build a client script which requesting files. 我也尝试过建立一个客户端脚本来请求文件。 When I'm requesting the html file, I receive it properly. 当我请求html文件时,我可以正确接收它。
But when I'm requesting the image file, it is being received but I can't view the image. 但是,当我请求图像文件时,它已被接收,但是我无法查看图像。

How can I receive the image as a file? 如何接收图像作为文件?

Relevant path of the server: 服务器的相关路径:

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.');
    }
});

Relevant part of the client: 客户相关部分:

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();

try to encode image in base64 string 尝试将图像编码为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