Sealyu

--- 博客已迁移至: http://www.sealyu.com/blog

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  618 随笔 :: 87 文章 :: 225 评论 :: 0 Trackbacks
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!!
posted on 2010-02-01 21:21 seal 阅读(612) 评论(0)  编辑  收藏 所属分类: GWT

只有注册用户登录后才能发表评论。


网站导航: