简体   繁体   中英

How do I get the URL for an image stored in a subdirectory of a google-cloud-storage bucket

I have images storied in directories within a bucket in google-cloud-storage. The images are not publicly viewable. It's my understanding that I can 'sign' the image and the resulting URL will be publicly viewable for a specified time. Nothing I've tried so far, however, seems to work. Attempts to access the URL result in a NoSuchKey error.

Here's an example of the code I've tried. Exactly what should the second parameter be that I pass to BlobInfo.newBuilder ? The documentation says it should be the object name . Is that just the name of the file, ie myimage.jpg ?

URL getSignedImageUrl(String uri) {
  // ImageUploadDetails contains metadata about the image
  ImageUploadDetails imageUploadDetails = ImageUploadDetails.findByUri(uri)
  if (imageUploadDetails) {
    BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(bucket, imageUploadDetails.thumbnailPath)).build()
    URL url = storage.signUrl(blobInfo, 60, TimeUnit.MINUTES, Storage.SignUrlOption.withV4Signature())
    return url // this URL, when converted to a String, doesn't work
} else {
  throw new ImageNotFoundException("Cannot open file: ${imageUploadDetails.thumbnailPath}")}
}

I expect the signed URL to be available to public users for the specified amount of time. I would like to use it as the src value within an image tag.

Instead, what I'm getting is:

<Error>
  <Code>NoSuchKey</Code>
  <Message>The specified key does not exist.</Message>
  <Details>
  obfuscated to protect the innocent
  </Details>
</Error>

By default, the url of an object would be https://storage.googleapis.com/${bucket.name}/${blob.name}

For example:

- bucket1
  - folder1
    - image1.jpg  https://storage.googleapis.com/bucket1/folder1/image1.jpg
    - image2.jpg  https://storage.googleapis.com/bucket1/folder1/image2.jpg
- bucket2
  - image3.jpg    https://storage.googleapis.com/bucket2/image3.jpg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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