将 ReadStream 从谷歌云存储上的文件传递到 POST FORM

Imi*_*Kim 5 node.js google-cloud-storage firebase

我正在尝试发送一个包含(原始)文件的 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,
 });
}
Run Code Online (Sandbox Code Playgroud)

如果我们首先下载文件(到云函数实例上的临时文件),然后使用 fs.createReadStream(fileAPath_tmp)

POST 失败(即端点没有以相同的方式接收文件,如果有的话),使用上面的代码(没有临时下载)使用 bucket.file(fileAPath).createReadStream()

小智 1

根据 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(.....));
Run Code Online (Sandbox Code Playgroud)

  • 管道需要像 WriteStream 这样的东西作为输入。然后我如何将文件的 Stream 提供给 POST 请求的 formData? (2认同)