如何查看存储在谷歌云存储桶中的图像?

2024-04-20 13:49:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个存储图像的存储桶,当我使用图像的公共URL检索图像时,它会在浏览器中下载图像,而不是在浏览器中显示图像,我如何查看图像而不是下载图像。我为上传的图像使用以下URL

https://www.googleapis.com/download/storage/v1/b/image-downloader-bucket/o/a06266f6-6082-468e-92ca-f918a48533a8?generation=1455661996337000&alt=media

有人能告诉我如何创建正确的URL来查看图像吗


Tags: https图像imagecomurlbucketdownloadwww
3条回答

与@ehero响应类似,但对于python,要点是在上载文件之前使用content_type blob属性:

from google.cloud import storage
storage_client = storage.Client.from_service_account_json('your/path/to/service/credentials.json')
bucket = storage_client.bucket('my-bucket-name')
blob = bucket.blob('my/path/in/storage.jpg')
blob.content_type = 'image/jpeg' # This one is the important
blob.upload_from_file(file) # Also available upload_from_filename

如果对象是公开可读的,则可以直接在“https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME”处查看它,在您的示例中,该位置是https://storage.googleapis.com/image-downloader-bucket/a06266f6-6082-468e-92ca-f918a48533a8

我的问题是我没有为对象设置mimetype。没有它,浏览器不知道它是一个图像,因此它下载文件而不是在浏览器窗口中显示它

加上这一点就成功了:

const blobStream = blob.createWriteStream({
  metadata: {
    contentType: "image/jpeg"
  }
});

相关问题 更多 >