Google cloud firestore 如何从多部分/formData请求在Firestore数据库中保存文件?

Google cloud firestore 如何从多部分/formData请求在Firestore数据库中保存文件?,google-cloud-firestore,google-cloud-functions,multipartform-data,form-data,Google Cloud Firestore,Google Cloud Functions,Multipartform Data,Form Data,我有一个firebase功能: //功能和firestore要求如下 exports.saveData=functions.https.onRequest(异步(req,res)=>{ console.log(“接收到的数据”) const-busboy=new-busboy({headers:req.headers}); 常量字段={} 常量上载={} //推送字段中不是文件的字段 营业员.on('field',(fieldname,val)=>{ log(`Processed field$

我有一个firebase功能:

//功能和firestore要求如下
exports.saveData=functions.https.onRequest(异步(req,res)=>{
console.log(“接收到的数据”)
const-busboy=new-busboy({headers:req.headers});
常量字段={}
常量上载={}
//推送字段中不是文件的字段
营业员.on('field',(fieldname,val)=>{
log(`Processed field${fieldname}:${val}.`);
字段[fieldname]=val;
});
//上传时推送文件
on('file',(字段名、文件名、文件名)=>{
log('File:',File);
const filepath=path.join(tmpdir,文件名);
上传[fieldname]=文件路径;
});
在('finish',()=>{
console.log(上传)
console.log(字段)
db.集合(“a_集合”)。添加({
a:菲尔兹,
b:菲尔兹,
文件:“帮助!从客户端,我发送一个图像。我需要保存哪个值?”
})
.然后(函数(){
res.send(“数据已保存”)
})
.catch(函数(错误){
资源状态(400).发送(错误)
console.error(“error:+error”)
})
});
端部(要求原车身);

})
您需要将其保存为Base64测试,以便将其上载到Firestore

所以,您可以做的是读取文件,将其转换为Base64,然后将其添加到Firestore数据库中

要获得基数64,可以使用

//Get Base64 of file
function getBase64(file){
    var reader = new FileReader();
    reader.onerror = function (error) {
       console.log('Error: ', error);
    };
    reader.readAsDataURL(file);
    reader.onload = function () {
        let encoded = reader.result.split(',');
        //you split this to get mimetype out of your base64
        addForSale(Date.now().toString(10), { uFile: encoded[1]});
        // I just used a timestamp as the ID
    }
};

另一种选择是将文件上载到云存储,并将文件在云存储中的位置保存在Firestore中