Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT: How to implement file download

Tags:

java

servlets

gwt

I am new to GWT and general web application.

I am making a GWT web application. One functionality it provides is to download file by clicking a button on the web page. Unfortunately, the file itself does not physically located on the server side. Server side needs to grab it through a REST call to another web service to get a InputStream of the file.

My question is that:

  1. How can I pass the stream to the client side so that the browser can start to download?
  2. Do I have to write the file physically on the server before start this?

Many thanks

EDIT: I have found this example: How to use GWT when downloading Files with a Servlet?

In this example, the file is physically located on the server side. The file I got from the web service via a stream is very large and I don't want to save them on my GWT server side. Any suggestions?


1 Answers

We use a servlet like the example above. Just make sure you set the header and the file name to be of the appropriate type. (The filename must end in the proper ending)

// process the data (In your case go get it)
byte[] data = generateReturnBuffer();
// do not cache
response.setHeader("Expires", "0");  
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");  
response.setHeader("Pragma", "public");
// content length is needed for MSIE
response.setContentLength(data.length);
// set the filename and the type
response.setContentType("application/pdf");  
response.addHeader("Content-Disposition", "attachment;filename=" + "fileName.pdf");  
ServletOutputStream out = resp.getOutputStream();
out.write(data);
out.flush();

where the response is the servlet HttpServletResponse.
Look here for the valid mime types.
At some point you will need to store the data in either a file or in memory since certain versions of internet explorer require the file length.

like image 110
Romain Hippeau Avatar answered Feb 03 '26 21:02

Romain Hippeau