如何通过管道将文件从节点上传到 Firebase Cloud?

问题描述 投票:0回答:1

TLDR;

这个问题是关于

firebase
API 的,我想知道它是否有一种 createWriteStream 之类的方式,我可以
pipe
一个 readStream 来上传文件。

完整问题

我只想将图像从我的

Node
服务器上传到我的
Firebase Cloud

现在,有两种方法可以解决这个问题:

  • 简单的方法:在开始上传之前将整个文件加载到内存中。
  • 复杂的方式:也是高性能的方式,就是使用流。

最简单的方法是......嗯,简单。
您只需使用 firebase 的

uploadBytesResumable
,如其文档中所示。

import fs from 'fs'; import path from 'path'; import { initializeApp } from 'firebase/app'; import { getStorage } from 'firebase/storage'; import { ref, uploadBytesResumable } from 'firebase/storage'; const firebaseApp = initializeApp(firebaseConfig); const storage = getStorage(firebaseApp); async function uploadImage() { // Step 1: load the ENTIRE file to upload const filepath = path.resolve(dirname, 'my-image.jpg'); const fileToUpload = fs.readFileSync(filepath); // Step 2: upload the entire file to Firebase Cloud const storageRef = ref(storage, `images/path/on/bucket/my-image.jpg`); await uploadBytesResumable(storageRef, fileToUpload); }
但是我想要的是第二种方式,即使用流。
但我陷入困境的是

pipe

阶段,因为我不知道我需要传递什么给它:

import fs from 'fs'; import path from 'path'; import { initializeApp } from 'firebase/app'; import { getStorage } from 'firebase/storage'; import { ref, uploadBytesResumable } from 'firebase/storage'; const firebaseApp = initializeApp(firebaseConfig); const storage = getStorage(firebaseApp); async function uploadImage() { // Step 1: load the file to upload in chunks/buffers const filepath = path.resolve(dirname, 'my-image.jpg'); const myReadStream = fs.createReadStream(filepath); // Step 2: upload stream to Firebase Cloud myReadStream.pipe(???) }
我在任何地方都找不到如何实现这一目标的示例......

我需要传递什么给
.pipe()

请帮忙。

node.js firebase npm google-cloud-firestore stream
1个回答
0
投票
要通过管道将文件从 Node.js 应用程序上传到 Firebase Cloud Storage,您可以使用适用于 Node.js 的 Firebase Admin SDK。此 SDK 允许您与 Firebase 服务交互,包括 Firebase 云存储。

const fileStream = fs.createReadStream(localFile); const uploadStream = bucket.file(remoteFile).createWriteStream({ contentType: 'application/octet-stream', // Set the content type as needed }); fileStream.pipe(uploadStream);
您可以监听“error”和“finish”等事件来处理上传过程中的错误和成功事件。

并且不要忘记确保在应用程序退出时正确处理 Firebase Admin SDK 的最终确定。

© www.soinside.com 2019 - 2024. All rights reserved.