【问题标题】:Pass ReadStream to a POST FORM from file on google cloud storage将 ReadStream 从谷歌云存储上的文件传递到 POST FORM
【发布时间】:2019-08-20 13:08:40
【问题描述】:

我正在尝试发送包含(原始)文件的 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),则 POST 会按预期工作

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

【问题讨论】:

    标签: node.js firebase google-cloud-storage


    【解决方案1】:

    根据 Google File Storage 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(.....));
    

    【讨论】:

    • 管道需要像 WriteStream 这样的东西作为输入。然后如何将文件的 Stream 提供给 POST 请求的 formData?
    • 我也有同样的问题。如何让.pipe()返回的流附加到HTTP响应中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2018-07-11
    • 2022-08-20
    • 1970-01-01
    相关资源
    最近更新 更多