Per some requests for the File Download opposite of File Upload.
On the server side I implemented the doGet method of the
HttpServlet class. I grab the raw data from the database and set it
into the response (with the appropriate response type):
BufferedOutputStream output = null;
try {
RawAttachmentItem attachment = attachmentFileDao.retrieveContents(fileid);
ByteArrayInputStream input = new ByteArrayInputStream(attachment.getContents());
int contentLength = input.available();
resp.reset();
resp.setContentType("application/octet-stream");
resp.setContentLength(contentLength);
resp.setHeader("Content-disposition", "attachment; filename=""" + attachment.getFilename()
+ """");
output = new BufferedOutputStream(resp.getOutputStream());
for(int data; (data=input.read()) != -1;) {
output.write(data);
}
output.flush();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
close(output);
}
On the client side, you simple create a new iFrame with its 'src' attribute set to the servlet url for downloading the file:
boolean frameExists = (RootPanel.get("downloadiframe") != null);
if(frameExists) {
Widget widgetFrame = (Widget)RootPanel.get("downloadiframe");
widgetFrame.removeFromParent();
}
NamedFrame frame = new NamedFrame("downloadiframe");
frame.setUrl(GWT.getModuleBaseURL()
+ "/attachmentHandler?action=dl&fileid="
+ model.getFileId());
frame.setVisible(false);
RootPanel.get().add(frame);
When the file gets sent back to the iFrame, the browser will treat
it as a file download and prompt you to do something with it (open,
save, cancel, etc).
If anyone has questions or requires more detail, please do not hesitate to ask!!