以下是如何将文件从驱动器上传到Firebase存储的方法:
let bucket = admin.storage().bucket();
let uploadRes = await bucket.upload(filePath, options);
你可以在
Google Cloud Storage文档中找到该选项的描述。您很可能会在Google Cloud控制台中创建具有权限的密钥并将文件导出为json格式。您可以在
Google Cloud平台控制台
->
IAM和管理
->
服务帐户
->
创建服务帐户
(使用密钥创建)。导出json后,按如下方式设置环境变量:
export GOOGLE_APPLICATION_CREDENTIALS='./the_exported_file.json'
请将此文件安全地存储在您的服务器上,因为它具有读取和写入访问权限!
以下是一个完整的上传功能示例,还将文件保存为其哈希名称。
<!-- language: typescript -->
import admin from "firebase-admin";
import path from 'path'
const sha256File = require('sha256-file');
const firebaseConfig = {
apiKey: "...",
authDomain: "abc.firebaseapp.com",
databaseURL: "https://abc.firebaseio.com",
projectId: "abc",
storageBucket: "abc.appspot.com",
messagingSenderId: "123",
appId: "1:123:web:xxx",
measurementId: "G-XXX"
};
admin.initializeApp(firebaseConfig);
async function uploadFile(filePath: string, uploadFolder: string, contentType: string, hash: string | undefined = undefined,)
: Promise<string> {
if (!hash) {
hash = await sha256File(filePath);
}
let bucket = admin.storage().bucket();
const ext = path.extname(filePath);
const uploadPath = uploadFolder + hash + ext;
const options = {destination: uploadPath};
console.debug("starting upload");
let uploadRes = await bucket.upload(filePath, options);
console.debug("finished upload");
let newMetadata = {
contentType: contentType
};
if(uploadRes) {
let file = uploadRes[0];
file.setMetadata(newMetadata).then(() => {
}).catch(function (error) {
console.error(error)
});
}
return uploadPath;
}
fs.readFile()
可以获取一个Buffer对象,您可以将其传递给HTTP请求方法以发送它。 - Patrick Evans