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

时间:2020-10-05 15:11:07

标签: javascript firebase google-chrome-extension firebase-storage

我创建了一个Chrome扩展程序,其中带有当前标签页的屏幕截图。然后,我想将图像上传到Firebase。

chrome.tabs.captureVisibleTab返回dataUrl字符串 [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来自此Stackoverflow 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错误,这是请求的样子: enter image description here

1 个答案:

答案 0 :(得分:0)

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

用于在客户端上提交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 Storage中上传,但是您实际上无法查看或下载它(您只能看到旋转的加载占位符)。

这些帖子对于实现此解决方案特别有帮助:

https://stackoverflow.com/a/46999645/1720985 https://github.com/firebase/firebase-admin-node/issues/694#issuecomment-583141427