Search code examples
gwtservletsgwt-rpcgwt2formpanel

Send a file from server to client in GWT


I am using GWT.

I have to download a file file from server to client.

Document is in the external repository.

Client sends the id of the document through a Servlet.

On server side: Using this ID document is retrieved:

Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();

ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();

int c;
while ((c = inputStream.read()) != -1) {
    System.out.print((char) c); 
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();

Here I can read the document.

I want to send this to the client. How do I make this a file and send it back to the client?


Solution

  • In Your Servlet:

    Document document =(Document)session.getObject(docId);
    ContentStream contentStream = document.getContentStream();
    String name = contentStream.getFileName();
    response.setHeader("Content-Type", "application/octet-stream;");
    response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
    OutputStream os = response.getOutputStream();
    InputStream is = 
      (ByteArrayInputStream) contentStream.getStream();
    BufferedInputStream buf = new BufferedInputStream(is);
    int readBytes=0;
    while((readBytes=buf.read())!=-1) {
          os.write(readBytes);
    }   
    os.flush();
    os.close();// *important*
    return;