这个问题是关于
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()
?请帮忙。
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 的最终确定。