[英]How can I save a buffer created by express-fileupload to a file?
I want to post this image to my nodejs express server using express-fileupload
, this is my node code:我想使用express-fileupload
将此图像发布到我的 nodejs express 服务器,这是我的节点代码:
app.post("/files", function(req, res) {
console.log(req.files.brandLogo)
const data = {
fieldname: 'file',
originalname: req.files.brandLogo.name,
encoding: req.files.brandLogo.encoding,
mimetype: req.files.brandLogo.mimetype,
buffer: req.files.brandLogo.data,
size: req.files.brandLogo.size
};
fs.writeFile("file", data, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
});
I can see the file posted being logged into the console, name, size, and everything is correct, but when I try to write this buffer to a file, the written file is a 1kb file and not the correct one.我可以看到发布的文件已登录到控制台,名称、大小和一切都是正确的,但是当我尝试将此缓冲区写入文件时,写入的文件是 1kb 文件而不是正确的文件。 Any ideas?有任何想法吗? Cheers.干杯。
I would suggest making a simple change to use JSON.stringify when writing to the output file, like so:我建议在写入 output 文件时进行简单的更改以使用 JSON.stringify ,如下所示:
app.post("/files", function(req, res) {
console.log(req.files.brandLogo)
const data = {
fieldname: 'file',
originalname: req.files.brandLogo.name,
encoding: req.files.brandLogo.encoding,
mimetype: req.files.brandLogo.mimetype,
buffer: req.files.brandLogo.data,
size: req.files.brandLogo.size
};
// Use JSON.stringify to serialize here.
fs.writeFile("file", JSON.stringify(data, null, 4), function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
});
Otherwise the data is converted to something like "[object Object]", which is not what we want!否则数据会被转换成类似“[object Object]”的东西,这不是我们想要的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.