繁体   English   中英

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

[英]Uploading image to Firebase Storage via POST request

我创建了一个 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 错误,这就是请求的样子: 在此处输入图片说明

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

在客户端提交 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://stackoverflow.com/a/46999645/1720985 https://github.com/firebase/firebase-admin-node/issues/694#issuecomment-583141427

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM