使用 NextJS API 发送文件作为响应 [英] Send file as response using NextJS API

查看:32
本文介绍了使用 NextJS API 发送文件作为响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如题,

在 NodeJs + Express 中,我可以使用以下行返回一个文件作为响应

In NodeJs + Express, i can return a file as response with the following line

res.sendFile(absolute_path_to_the_file)

如果我想从 NextJs 目录中的输出文件夹返回单个图像,我如何使用 NextJs API 实现这一点?我只能将 res.send() 和 res.json() 视为返回响应的方式,我不确定如何利用它将图像作为响应返回给调用者.

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.

如果我喜欢这个

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.

在此需要帮助.

推荐答案

在这里回答我自己的问题给那些也想知道的人..

Answering my own question here for those who're curious to know too..

我在 NextJS 中发了一个帖子,他们给了我一个很好的答案 - 这里

I made a thread about it in NextJS and they gave me a good answer to this - here

两种方法是使用 readStream

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

或者把对象改成buffer,使用send方法

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

这两个答案都适用于我的情况.使用 process.cwd() 导航到需要作为响应发送的文件/图像.

Both answers work in my case. Use process.cwd() to navigate to the files / image that needed to be send as response.

这篇关于使用 NextJS API 发送文件作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆