微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将位于 Firebase Cloud Storage 中的文件发送到另一个网站

如何解决将位于 Firebase Cloud Storage 中的文件发送到另一个网站

我一直在尝试这个,我没有找到任何好的教程。

我正在尝试使用 Cloud Functions 和 axios 的 Cloud Storage 触发器 onFinalize 发送位于 Google Cloud Storage 中的文件。 问题是将文件附加到 formData 中。

首先,我使用 NodeJS 和 Express 在我自己的后端完成了它,并且它有效。但我也使用了 Multer,但我不知道我是否可以在这里、在 Cloud Storage 触发器中使用 Multer,或者这样做是否有意义。

function to(promise) {
  return promise.then(data => {
    return [null,data];
  })
    .catch(err => [err]);
}


exports.onUploadFileDetectAndCreateCorrectAction = functions.storage.object().onFinalize(async (object) => {
  const fileBucket = object.bucket; // The Storage bucket that contains the file.
  const filePath = object.name; // File path in the bucket.
  const contentType = object.contentType; // File content type.

  // Get the file name.
  const fileName = path.basename(filePath);

  const bucket = admin.storage().bucket(fileBucket);
  const tempFilePath = path.join(os.tmpdir(),fileName);
  const Metadata = {
    contentType: contentType,};

  let targetFile = bucket.file(filePath);
  let [error,dataDown] = await to(bucket.file(filePath).download({ destination: tempFilePath }));
  if (error) throw new Error('Error al descargar archivo al tmpFilePath: ',error);

  fs.readFile(tempFilePath,async (error,dataBuffer) => {
    if (error) console.log("Error al pedir e lbuffer:",dataBuffer);
    log("Data Buffer: ",dataBuffer);
    const formData = new FormData();
    
    formData.append("title","2");
    formData.append("cover",dataBuffer,'primerImagen');

    const response = await axios.post('https://api...',formData,{
      headers: {
        ...formData.getHeaders(),"Content-Type": "multipart/form-data",}
    });
  })

});

我正在记录 dataBuffer,我认为这是正确的,因为大小是我上传的图像的大小,但 formData 仍然失败。

我得到的错误是:

错误:请求失败,状态码为 415 在 createError (/workspace/node_modules/axios/lib/core/createError.js:16:15) 在解决 (/workspace/node_modules/axios/lib/core/settle.js:17:12) 在 IncomingMessage.handleStreamEnd (/workspace/node_modules/axios/lib/adapters/http.js:260:11) 在 IncomingMessage.emit (events.js:326:22) 在 IncomingMessage.EventEmitter.emit (domain.js:506:15) 在 endReadableNT (_stream_readable.js:1241:12) 在 processticksAndRejections (internal/process/task_queues.js:84:21)

我尝试了 createReadStream,这是 CloudStorage文件 API 中提到的一种方法。问题在于,当您在 express 中使用 multer 时,来自 CloudStorage 的文件没有称为缓冲区的方法作为文件

  formData.append("cover",bucket.file(filePath).createReadStream(),fileName);
  
  

还尝试使用 fs.createReadStreamreadFile 传递缓冲区:

  formData.append("cover",fs.createReadStream(filePath),fileName);
  formData.append("cover",fs.readFile(filePath),fileName);
  
  

但也不起作用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。