3 回答
TA贡献1842条经验 获得超12个赞
看起来您只想授予用户下载文件的权限。
解决方案是使用Signed URL,它可以让您向用户提供一个 URL 以在有限的时间内访问/下载对象。如果您将用户直接重定向到该 URL,下载将立即开始。
TA贡献1799条经验 获得超6个赞
我将代码更改为:
public static String downloadFile(Storage storage, String fileName){
Blob blob = storage.get(BUCKET_NAME, fileName);
String PATH_TO_JSON_KEY = "/your/path";
URL signedUrl = null;
try {
signedUrl = storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME, fileName).build(),
1, TimeUnit.DAYS, SignUrlOption.signWith(ServiceAccountCredentials.fromStream(
new FileInputStream(PATH_TO_JSON_KEY))));
} catch (IOException e) {
e.printStackTrace();
}
return signedUrl.toString();
}
TA贡献1815条经验 获得超6个赞
#将此行添加到 spring-boot application.properties 文件 spring.cloud.gcp.credentials.location=classpath:key.json
// read/download objects
public static ResponseEntity<byte[]> getObjectFromGCP(String yourfileName) throws IOException {
String objectNameWithLocation ="your file location with file name in GCP bucket";
//create your storage object with your credentials
Credentials credentials = GoogleCredentials.fromStream(new
ClassPathResource("key.json").getInputStream());
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
BlobId blobId = BlobId.of(bucketName, objectNameWithLocation);
Blob blob = storage.get(blobId);
return ResponseEntity.ok().contentType(MediaType.valueOf(FileTypeMap.getDefaultFileTypeMap().getContentType(yourfileName)))
.body(blob.getContent(BlobSourceOption.generationMatch()));
}
添加回答
举报