如何通过multipart / formData请求将文件保存在Firestore数据库中?

问题描述 投票:0回答:1

我有一个firebase功能:

//Functions and firestore requirements are here

exports.saveData = functions.https.onRequest(async (req, res) => {
  console.log("Data received")
  const busboy = new Busboy({headers: req.headers});
  const fields = {}
  const uploads = {}

  //Push fields that are not file in fields
  busboy.on('field', (fieldname, val) => {
    console.log(`Processed field ${fieldname}: ${val}.`);
    fields[fieldname] = val;
  });
  //Push files in uploads
  busboy.on('file', (fieldname, file, filename) => {
    console.log('File :', file);
    const filepath = path.join(tmpdir, filename);
    uploads[fieldname] = filepath;
  });
  busboy.on('finish', () => { 
    console.log(uploads)
    console.log(fields)
    db.collection("a_collection").add({
        a: fields.a,
        b: fields.b,
        file: "Help ! From the client, I send an image. Which value do I need to save ?"
    })
    .then(function () {
        res.send("Data is saved")
    })
    .catch(function (error) {
        res.status(400).send(error)
        console.error("Error :" + error)
    })
  });

  busboy.end(req.rawBody);
  

})

我想将来自multipart / formData请求的图像和数据保存在Firestore数据库中。我怎样才能做到这一点 ?我需要保存base64图像还是有其他方法将文件保存在Google Cloud Firestore中?

我的英语不太好,抱歉:/

google-cloud-firestore google-cloud-functions multipartform-data form-data
1个回答
0
投票

您需要将其保存为Base64测试,才能将其上传到Firestore。

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

要获得Base 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
    }
};

另一种选择是将文件上传到Cloud Storage并将文件在Cloud Storage中的位置保存在Firestore中。

© www.soinside.com 2019 - 2024. All rights reserved.