【问题标题】:How to save a file in a Firestore database from a multipart/formData request?如何从 multipart/formData 请求将文件保存在 Firestore 数据库中?
【发布时间】:2020-01-28 22:29:02
【问题描述】:

我有一个火力基地功能:

//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】:

    您需要将其保存为 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 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2019-08-30
      • 2018-11-14
      • 1970-01-01
      • 2012-05-19
      相关资源
      最近更新 更多