简体   繁体   中英

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).
When I'm requesting the files with the browser, I'm able to view the html file or the requested image.

I've tried also to build a client script which requesting files. When I'm requesting the html file, I receive it properly.
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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