简体   繁体   中英

How to download a file from Google Cloud Storage and return it in Spring controller

I have a Spring Boot application. Users can login to my application and upload files. All the files of users are stored in a Google Cloud Storage. Now, I want the users to be able to download their files. So, I have to download the files form the Cloud Storage. I don't know how my controller should look. With my current code I'm getting an empty file. The upload is already made and the connection is fine as well.

public static Blob downloadFile(Storage storage, String fileName){
        Blob blob = storage.get(BUCKET_NAME, fileName);
        return blob;
    }

@RequestMapping(value = "/downloadFileTest")
    @ResponseBody
    public void downloadFile(HttpSession session,
            HttpServletResponse response) {
        Storage storage = de.msm.msmcenter.service.cloudstorage.Authentication.getStorage();
        Blob blob = de.msm.msmcenter.service.cloudstorage.Authentication.downloadFile(storage,"test.txt");
        ReadChannel readChannel = blob.reader();
        InputStream inputStream = Channels.newInputStream(readChannel);
        try {
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=test.txt");
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
            inputStream.close();
        } catch (Exception e){
            e.printStackTrace();
        }

    }

I actually want to be able to download any file, not only txt. When the user opens the link, the file with the name test.txt gets downloaded but it's empty..

It seems like you just want to give access to the user to be able to download the file.

A solution for that would be to use a Signed URL , which can let you provide the user with an URL to access/download the object for a limited time. If you redirect the user directly to that URL the download would start immediately.

Thank you @Mayeru I changed my code to :

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();
    }

//add this line to you spring-boot application.properties file 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()));
}

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