我正在尝试发送包含(原始)文件的 POST 表单,这些文件位于谷歌云存储桶中
此代码在 firebase 云函数中运行 - 我不想将存储文件下载到云函数实例然后通过表单上传(有效),而是直接将表单传递给 Stream
async function test() {
const rp = require('request-promise');
const path = require('path');
const { Storage } = require('@google-cloud/storage');
const storage = new Storage();
const bucketName = 'xxx';
const bucket = storage.bucket(bucketName);
const fileAPath = path.join('aaa', 'bbb.jpg');
let formData = {
fileA: bucket.file(fileAPath).createReadStream(),
};
return rp({
uri: uri,
method: 'POST',
formData: formData,
});
}
如果我们先下载文件(到云函数实例上的临时文件)然后使用 fs.createReadStream(fileAPath_tmp)
使用 bucket.file(fileAPath).createReadStream() 使用上述代码(无临时下载)时,POST 失败(即终点未以相同方式接收文件,如果有的话)
最佳答案
基于 Google 文件存储文档 createReadStream
,您需要像使用事件发射器一样使用读取流来填充缓冲区以返回给最终用户。您应该能够使用 .pipe()
方法将其直接通过管道传输到 HTTP 响应,类似于您现有的源代码。
remoteFile.createReadStream()
.on('error', function(err) {})
.on('response', function(response) {
// Server connected and responded with the specified status and headers.
})
.on('end', function() {
// The file is fully downloaded.
})
.pipe(.....));
关于node.js - 将 ReadStream 从谷歌云存储上的文件传递到 POST FORM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55420022/