簡體   English   中英

谷歌雲存儲圖像 url 工作正常,但是當在 img html 文件的 src 中使用時,它會轉到替代項並且不顯示圖像

[英]google cloud storage image url works fine but when used in the src of an img html file it goes to the alternative and does not show the image

我有一個 PRN JS 應用程序,從前面(在反應中)一個表單有一個輸入類型文件,它將文件(圖像)發送到服務器端。 然后,我將圖像上傳到谷歌雲存儲中的存儲桶中,並為所有用戶提供所有內容的公共許可。 它可以正常上傳,如果我將 go 上傳到由 google 存儲提供的公共 url,即使在隱身 window 上,我也可以看到圖片。 問題是當我將路徑發送到反應組件以顯示圖像時。 它有一個 img html 標簽,該標簽轉到 img html 標簽的替代文本屬性,並且該組件從不顯示我想要的圖像。 它在 Google Cloud Sotorage Bucket 中以 20 B 的奇怪大小上傳。

我的代碼:

const router = require('express').Router();
const {Storage} = require('@google-cloud/storage');

const gc = new Storage({
  projectId: GOOGLE_CLOUD_PROJECT_ID,
  keyFilename: GOOGLE_CLOUD_KEYFILE,
})
getPublicUrl = (bucketName, fileName) => `https://storage.googleapis.com/best-buds/${bucketName}/${fileName}`


router.post('/', async (req, res, next) => {
    try {
        
        const file = req.files && req.files.image
        const bucket = gc.bucket('best-buds');
        const file_bucket = file && bucket.file(file.name)
        const stream = file_bucket.createWriteStream({
          resumable: false,
          gzip: true
        })
        stream.on('finish', () => {
          file.cloudStorageObject = file.name;
          return file_bucket.makePublic()
          .then(() => {
            file.gcsUrl = getPublicUrl('best-buds',file.name);
            next()
          })
        })

        stream.end(file.buffer);


        ...
        res.sendStatus(200);
    } catch (error) {
        next(error);
        res.sendStatus(500);
    }
    
});

module.exports = router;

我使用了 devtools 擴展並檢查了我的反應組件接收到正確的 url 的 de props 圖像。 如果我使用瀏覽器從 go 到 url 我可以看到圖像,但它仍然沒有顯示在我的組件中。

有人可以幫我嗎?

這里的問題是上傳,將文件上傳到谷歌雲存儲,無論是雲存儲還是 firebase 存儲,您需要將文件作為 blob 傳遞,然后您需要使用適當的元數據為其分配適當的擴展名,每種文件類型都有它自己的元數據,例如:pdf 文檔將具有 document/pdf 或圖像將具有 image/png 或 image/jpeg。 如果上傳失敗並且您獲得了一些低字節大小的文件,那么這意味着上傳失敗並且實際上是由於元數據。

 var metadata = {
  contentType: 'image/jpeg',
};

Firebase 的文檔在這里解釋了它是如何工作的


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM