As titled,
In NodeJs + Express, i can return a file as response with the following line
res.sendFile(absolute_path_to_the_file)
How can i achieve this with NextJs API, assuming if i want to return a single image from output folder inside NextJs directory? I can only see res.send() and res.json() as ways to return response, and im not sure how can i leverage it to return image as response back to the caller.
if i do like this
res.send(absolute_path_to_the_file)
It will just send me the string of the directory path. What i expect is the image send from the directory denoted by the directory path.
Need help here for this.
Answering my own question here for those who're curious to know too..
I made a thread about it in NextJS and they gave me a good answer to this - here
2 ways of doing this is either by using readStream
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
or change the object into buffer and use send method
/*
Project structure:
.
├── images_folder
│ └── next.jpg
├── package.json
├── pages
│ ├── api
│ │ └── image.js
│ └── index.js
├── README.md
└── yarn.lock
*/
// pages/api/image.js
import fs from 'fs'
import path from 'path'
const filePath = path.resolve('.', 'images_folder/next.jpg')
const imageBuffer = fs.readFileSync(filePath)
export default function(req, res) {
res.setHeader('Content-Type', 'image/jpg')
res.send(imageBuffer)
}
Both answers work in my case. Use process.cwd()
to navigate to the files / image that needed to be send as response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With