我一直在尝试使用可调用的Firebase云功能将文件上传到 Firebase存储。
我要做的就是使用axios
从URL提取图像并尝试上传到存储。
我面临的问题是,我不知道如何保存来自axios的响应并将其上传到存储。
首先,如何将接收到的文件保存在os.tmpdir()
创建的temp目录中。
然后如何将其上传到存储。
在这里,我以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.');
}
});