【发布时间】:2020-02-29 22:08:15
【问题描述】:
我一直在尝试使用可调用的 firebase 云函数将文件上传到 Firebase 存储。
我所做的只是使用axios 从 URL 中获取图像并尝试上传到存储。
我面临的问题是,我不知道如何保存来自 axios 的响应并将其上传到存储。
首先,如何将接收到的文件保存在os.tmpdir()创建的临时目录中。
然后如何将其上传到存储中。
在这里,我以arraybuffer 的形式接收数据,然后将其转换为 Blob 并尝试上传。
这是我的代码。我认为我错过了一个主要部分。
如果有更好的方法,请推荐我。我一直在查看大量文档,但没有找到明确的解决方案。请指导。提前致谢。
const bucket = admin.storage().bucket();
const path = require('path');
const os = require('os');
const fs = require('fs');
module.exports = functions.https.onCall((data, context) => {
try {
return new Promise((resolve, reject) => {
const {
imageFiles,
companyPIN,
projectId
} = data;
const filename = imageFiles[0].replace(/^.*[\\\/]/, '');
const filePath = `ProjectPlans/${companyPIN}/${projectId}/images/${filename}`; // Path i am trying to upload in FIrebase storage
const tempFilePath = path.join(os.tmpdir(), filename);
const metadata = {
contentType: 'application/image'
};
axios
.get(imageFiles[0], { // URL for the image
responseType: 'arraybuffer',
headers: {
accept: 'application/image'
}
})
.then(response => {
console.log(response);
const blobObj = new Blob([response.data], {
type: 'application/image'
});
return blobObj;
})
.then(async blobObj => {
return bucket.upload(blobObj, {
destination: tempFilePath // Here i am wrong.. How to set the path of downloaded blob file
});
}).then(buffer => {
resolve({ result: 'success' });
})
.catch(ex => {
console.error(ex);
});
});
} catch (error) {
// unknown: 500 Internal Server Error
throw new functions.https.HttpsError('unknown', 'Unknown error occurred. Contact the administrator.');
}
});
【问题讨论】:
标签: javascript firebase google-cloud-functions firebase-storage