1
votes

I have an Google App Engine (Java) based application which stores the file data in Google Cloud storage.

This file download servlet works fine in my local eclipse environment and when deployed to appspot domain, this works for simple text files but for any documents (displayed in the browser in a new tab), but if I try with any other binary files (doc, jpeg, gif etc) seem to do nothing, no error is thrown as well at the server side . I checked directly in the file folders in Google Cloud storage, files are stored properly and able to access it directly, but cannot do so via the app engine.

Can you please let me know if I am missing something?

The code snippet below,

         try {
             FileService newfileService = FileServiceFactory.getFileService();
             AppEngineFile file = new AppEngineFile(cloudpath) ;
             FileReadChannel channel = newfileService.openReadChannel(file, false);
             BufferedInputStream bis = new BufferedInputStream(Channels.newInputStream(channel));
             BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream());
             resp.setHeader("Content-Disposition", "inline;filename=\"" + file.getNamePart() + "");
             int b = 0;
             while((b = bis.read()) != -1) {
                 bos.write(b);
             }
             bos.flush();
         } catch (Exception e) {
             e.printStackTrace();
         }
2

2 Answers

1
votes

Instead of trying to stream the file yourself you should use the BlobstoreService.serve method. This takes care or streaming and can be used on files of any size.

Something like

BlobstoreService blobService = BlobstoreServiceFactory.getBlobstoreService();
blobService.serve(blobService.createGsBlobKey(cloudpath), resp);
0
votes

you'll try the following order of statements.

...
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "inline;filename=\"" + file.getNamePart() + "");
BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream());

int b=0;
...