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

标签 node.js firebase google-cloud-storage

我正在尝试发送包含(原始)文件的 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 失败(即终点未以相同方式接收文件,如果有的话)

最佳答案

基于 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/

相关文章:

google-bigquery - 将 10 个数据集(每个数据集有 80 个表)从 bigquery 导出到谷歌存储的有效方法?

c# - 是否可以在HttpClient中访问解压前的压缩数据?

javascript - 如何为 Electron 应用程序提供 Django

node.js - mongoose的save()方法从何而来?

javascript - 如何在 Angular Firebase 中向前台发送后台通知以在 Angular 9 webapp 中显示通知?

angularjs - 在 firebase 中使用 $location.path() 进行重定向

c++ - Node : Why nodejs c++ addon is so slow?

javascript - arangodb难度教程: Node. js (io.js) 10分钟

javascript - Firebase:Cloud Firestore 触发器不适用于 FCM

java - 如何通过 Java API 将 block 上传到 Google Cloud Storage?