正如标题所示,
在 NodeJs + Express 中,我可以使用以下行返回一个文件作为响应
res.sendFile(absolute_path_to_the_file)
假设我想从 NextJs 目录中的输出文件夹返回单个图像,如何使用 NextJs API 实现此目的?我只能将 res.send() 和 res.json() 视为返回响应的方式,并且我不确定如何利用它来将图像作为响应返回给调用者。
如果我喜欢这个
res.send(absolute_path_to_the_file)
它只会向我发送目录路径的字符串。我期望的是从目录路径表示的目录发送的图像。
为此需要帮助。
在这里为那些也想知道的人回答我自己的问题。
我在 NextJS 中发表了一篇关于它的帖子,他们给了我一个很好的答案 -here https://github.com/vercel/next.js/discussions/15453#discussioncomment-41926
执行此操作的两种方法是使用 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);
或者将对象更改为缓冲区并使用 send 方法
/*
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()
导航到需要作为响应发送的文件/图像。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)