Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send file as response using NextJS API

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.

like image 868
Fred A Avatar asked Jul 24 '20 04:07

Fred A


1 Answers

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.

like image 157
Fred A Avatar answered Nov 15 '22 18:11

Fred A