Send image file as an API response in Node.js
📅August 16, 2022
Today we will show you how to send image file as API response in Node.js with Express.js framework. You may need to report an image file or a PDF file as an API response so you can use the following functions to send the file directly.
Way to send image file as an API response in Node.js
- function">Using res.sendFile() function
- Using res.send() function
1. Using res.sendFile() function
Use the res.sendFile() function to transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension. Unless the root option is set in the options object, path must be an absolute path to the file.
app.get('/report/:chart_id', function (req, res) {
// res.sendFile(filepath);
});
2. Using res.send() function
In the second solution, we can use the res.send() function to send file by passing HTML content.
app.get('/report/:chart_id', function (req, res) {
// res.send(`<img src="public/images/${imageName}">`);
});
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂