【发布时间】:2020-09-10 08:13:06
【问题描述】:
我正在本地保存一个图像文件,因此我可以使用 fs.createReadStream() 准备它并将其附加到我的 FormData 以将其发送到 REST api。像这样:(我正在使用 trello api https://developer.atlassian.com/cloud/trello/rest/#api-cards-id-attachments-post)
const fetch = require('node-fetch');
const Jimp = require('jimp');
const FormData = require('form-data');
// Save file locally
await Jimp.read(imagePNGURL).writeAsync(savedImagePath);
// Append it to the formdata using fs.createReadStream
const formData = new FormData();
formData.append('file', fs.createReadStream(savedImagePath));
// Send formData to api and image gets saved correctly
await fetch('TrelloUrl', { method: 'POST', body: formData })
现在我想做同样的事情,但不在本地保存文件,而是使用图像缓冲区。我尝试了以下方法,但似乎无法使其工作:
const fetch = require('node-fetch');
const Jimp = require('jimp');
const FormData = require('form-data');
const stream = require('stream');
// Save file to Buffer
const buffer = await Jimp.read(imagePNGURL).getBufferAsync('image/png');
// Convert buffer to stream
const bufferStream = new stream.PassThrough();
bufferStream.end(buffer);
// Try to append it to the formdata and send it to the api
const formData = new FormData();
formData.append('file', bufferStream); // Results in 400 Bad Request
formData.append('file', bufferStream.read()); // Results in empty image being uploaded
await fetch('TrelloUrl', { method: 'POST', body: formData })
---------
// Also tried to convert the buffer to stream like this:
const { Readable } = require('stream');
const bufferToStream = (buffer) => {
const stream = new Readable();
stream.push(buffer);
stream.push(null);
return stream;
};
formData.append('file', bufferToStream(buffer)); // Results in 400 Bad Request
formData.append('file', bufferToStream(buffer).read(); // Results in empty image being uploaded
如何将buffer 正确转换为fs.ReadStream() 对象,以便成功将其发送到api?
或者有更好的方法来解决这个问题?
感谢所有帮助。
【问题讨论】:
标签: javascript node.js buffer form-data node-streams