通过 POST 请求将图像上传到 Firebase 存储

Uploading image to Firebase Storage via POST request

我创建了一个 Chrome 扩展程序,可以截取当前选项卡的屏幕截图。然后我想将图片上传到 Firebase。

chrome.tabs.captureVisibleTab returns at dataUrl string [docs],我尝试将其作为 formData 包含在 POST 请求中,如下所示:

screenshotBtn.onclick = function(){
  // generate the screenshot
  chrome.tabs.captureVisibleTab(null, { format: 'png', quality: 80 }, function(dataUrl){
    // console.log(dataUrl);

    // create imageBlob from data
    let imgBlob = b64toBlob(dataUrl.replace('data:image/png;base64,', ''), "image/png");
    console.log('imgBlob: ', imgBlob);
    
    let formData = new FormData();
    formData.append('image', imgBlob);

    // upload to Firebase Storage
    let url = endpoint + '/uploadImage';
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': false
      },
      body: formData
    })
    .then((response) => response.json())
    .then(data => {
      console.log(data);
    });
  });
};

(函数b64toBlob取自这个Whosebug Post

我尝试按如下方式处理图像并将其上传到我服务器上的 Firebase:

app.post("/api/uploadImage", (req, res) => {
    (async () => {
        try {
            console.log(req.body.image);
            // req.body.image = image in base64 format
            await uploadFile(req.body.image);
            return res.status(200).send();
        } catch(error){
            console.log(error);
            return res.status(500).send(error);
        }
    })();
});

async function uploadFile(imageBlob){
    const metadata = {
        metadata: {
            firebaseStorageDownloadTokens: uuid()
        },
        contentType: 'image/jpeg',
        cacheControl: 'public, max-age=31536000'
    };

    await bucket.upload(imageBlob, {
        gzip: true,
        metadata: metadata,
    });
}

我无法判断问题是否是

  1. 使用 POST 请求的格式化方式
  2. 通过服务器接收文件的方式

我目前收到 500 错误,请求如下所示:

我能够拼凑出一个可行的解决方案。

在客户端提交POST请求:

screenshotBtn.onclick = function(){
  // generate the screenshot
  chrome.tabs.captureVisibleTab(null, { format: 'png', quality: 80 }, function(dataUrl){

    let body = {
      "image" : dataUrl
    };

    // upload to Firebase Storage
    let url = endpoint + '/uploadImage';
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(body)
    })
    .then((response) => response.json())
    .then(data => {
      console.log(data);
    });
  });
};

在服务器上:

// upload to storage
app.post("/api/uploadImage", (req, res) => {
    let image = req.body.image;
    let base64EncodedImageString = image.replace('data:image/png;base64,', '');
    let imageBuffer = new Buffer.from(base64EncodedImageString, 'base64');    
    let file = bucket.file("test-image.png");

    file.save(imageBuffer, {
        metadata: { 
            metadata: {
                firebaseStorageDownloadTokens: uuid
            },
        contentType: 'image/png',
        cacheControl: 'public, max-age=31536000',
        public: true,
        validation: 'md5'
        }
    }, (error) => {
        if(error){
            res.status(500).send(error);
        }
        return res.status(200).send('finished uploading');
    });
});

其中 bucketadmin.storage().bucket()(并且 adminfirebase-admin 的实例,已使用我的凭据正确初始化)

请注意,除非提供 uuid,否则图片会被列为已上传到 Firebase 存储中,但您无法实际查看或下载它(您只会看到一个旋转的加载占位符)。

这些帖子对解决这个问题特别有帮助:

https://github.com/firebase/firebase-admin-node/issues/694#issuecomment-583141427