Issue
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..
Solution
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.
Answered By - Mayeru
Answer Checked By - David Marino (JavaFixing Volunteer)