xgeek652
xgeek652

Reputation: 365

View and not download Google Cloud Storage files in browser

I'am working with NodeJs/ express to create a POST api endpoint to upload files to google cloud storage and returning a public URL like this : https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]

When the upload is done, I get the URL and when I open it , the file is downloaded directly (image, pdf etc...)

Is there a way to view and open it in the browser ?

here is my upload function :

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)

})

Thanks

Upvotes: 9

Views: 6444

Answers (1)

Brandon Yarbrough
Brandon Yarbrough

Reputation: 38389

If the URL looks like the code above, https://storage.googleapis.com/bucketName/objectName, a browser should be able to view it directly, so long as a few conditions are in place:

  • The object's contentType is set appropriately. If you don't specify a type, the default is application/octet-stream, and web browsers will probably decide to just download such an object rather than displaying it in some form.
  • The object's metadata does not override the contentDisposition. It's possible to force objects to be downloaded as attachments by setting that property to something like attachment; filename=foo.txt.
  • The object is either publicly viewable or appropriate credentials are passed in the GET request. This is not the default setting. When you upload the object, you'll need to explicitly note that the ACL should allow the group allUsers read permission. Alternately, you could set the default object ACL property of the bucket to include that permission.

In your case, the object is downloading successfully, so it's not the ACL issue, and if you don't know about the contentDisposition setting, then it's probably problem #1. Make sure you specify a reasonable content type for the object.

Example:

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

Upvotes: 10

Related Questions