在浏览器中查看而不是下载Google Cloud Storage文件

7

我正在使用NodeJs/express创建一个POST api端点,用于上传文件到Google云存储,并返回像这样的公共URL: https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]

当上传完成后,我获取URL,然后打开它时,文件会直接下载(图像、PDF等...)

有没有一种方法可以在浏览器中查看和打开它?

这是我的上传函数:

const uploadImage = (file) => new Promise((resolve, reject) => {
  const { originalname, buffer } = file

  const blob = bucket.file(originalname.replace(/ /g, "_"))
  const blobStream = blob.createWriteStream({
    resumable: false
  })

  blobStream.on('finish', () => {
    const publicUrl = format(
      `https://storage.googleapis.com/${bucket.name}/${blob.name}`
    )
    resolve(publicUrl)
  })
  .on('error', () => {
    reject(`Unable to upload image, something went wrong`)
  })
  .end(buffer)

})

谢谢。

感谢。

1个回答

8
如果URL看起来像上面的代码,https://storage.googleapis.com/bucketName/objectName,只要满足以下几个条件,浏览器就能够直接查看它:
  • 对象的contentType设置得当。如果您不指定类型,则默认为application/octet-stream,而Web浏览器可能会决定仅下载这样的对象,而不是以某种形式显示它。
  • 对象的元数据没有覆盖contentDisposition。可以通过将该属性设置为类似于attachment; filename=foo.txt的内容来强制下载对象作为附件。
  • 对象要么是公开可见的,要么在GET请求中传递了适当的凭据。这不是默认设置。上传对象时,您需要明确指出ACL应允许组allUsers读取权限。或者,您可以将存储桶的默认对象ACL属性设置为包含该权限。

在您的情况下,对象已经成功下载,因此这不是ACL问题,如果您不知道contentDisposition设置的问题,那么可能是问题#1。请确保为对象指定合理的内容类型。

示例:

const blobStream = blob.createWriteStream({
  resumable: false
  contentType: "text/html"
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接