【发布时间】:2021-11-08 08:04:11
【问题描述】:
我有一个 React 前端,允许用户使用 FormData() 将图像发送到节点后端。
在Express后端的控制器中,我使用multer作为中间件将图像抓取到files变量中:
private initializeRoutes() {
this.router.post(`${this.path}/image`, multerUpload.array("filesToUpload[]"), this.saveImage);
}
在后端的服务中,我正在尝试将files[0] 保存到uploads 文件夹中:
public saveImage(files: any) {
console.log("OtherServiceLocal saveImage - files :");
console.log(files[0]); // see screenshot at bottom for output
let localPath = fs.createWriteStream("./uploads/image.png");
files[0].buffer.pipe(localPath);
}
我尝试使用管道 file[0] 和 file[0].buffer 无济于事,即使经过一些研究,我也很难理解如何将其转换为流。
这是console.log(files[0]);的输出
{
fieldname: 'filesToUpload[]',
originalname: 'Screen Shot 2021-09-08 at 3.42.48 PM.png',
encoding: '7bit',
mimetype: 'image/png',
buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 03 85 00 00 02 c5 08 06 00 00 00 74 ff 46 78 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 62 ... 249405 more bytes>,
size: 249455
}
请注意,我知道您可以使用 multer 的 upload 方法将图像作为中间件直接保存在路由器中,但由于我的应用程序的某些要求,我不能这样做。
谢谢,
【问题讨论】:
-
检查这个answer它可能会有所帮助
标签: node.js image express file-upload fs