I am attempting to download a file from Google Cloud Storage. I'm using Google's Github code here on line 1042. I believe my error is with the file path. The path variable is to state where the file is downloaded to and the new name of it, correct? Note, I'm using a JSP button to start the process. To make it easier to solve for myself I replaced the String and Path variables with Strings instead of the HttpServletRequest.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// [START storage_download_file]
// The name of the bucket to access
String bucketName = "media";
// The name of the remote file to download
String srcFilename = "File.rtf";
// The path to which the file should be downloaded
Path destFilePath = Paths.get("/Volumes/Macintosh HD/Users/ab/Desktop/File.rtf");
// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();
// Get specific file from specified bucket
Blob blob = storage.get(BlobId.of(bucketName, srcFilename));
// Download file to specified path
blob.downloadTo(destFilePath);
// [END storage_download_file]
}
Caused by: java.nio.file.NoSuchFileException: /Volumes/Macintosh HD/Users/ab/Desktop/File.rtf
Code found on GitHub in the Google APIs. The part and concept I was missing is
OutputStream outStream = response.getOutputStream();
This sends the data back to the client's browser.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**** Define variables ****/
Storage storage = StorageOptions.getDefaultInstance().getService();
String bucketName = "bucketName";
String objectName = "objectName";
/**** Setting The Content Attributes For The Response Object ****/
String mimeType = "application/octet-stream";
response.setContentType(mimeType);
/**** Setting The Headers For The Response Object ****/
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", objectName);
response.setHeader(headerKey, headerValue);
/**** Get the Output Stream of the Response Object****/
OutputStream outStream = response.getOutputStream();
/**** Call download method ****/
run(storage, bucketName, objectName, outStream);
}
private void run(Storage storage, String bucketName, String objectName, OutputStream outStream)throws IOException {
/**** Getting the blob ****/
BlobId blobId = BlobId.of(bucketName, objectName);
Blob blob = storage.get(blobId);
/**** Writing the content that will be sent in the response ****/
byte[] content = blob.getContent();
outStream.write(content);
outStream.close();
}