如何用JSP实现JSP下载文件功能?

lhua_1225 2007-10-11 12:19:34
如何实现下述功能:
1)点击按钮,并取得服务器上的文件
2)出现保存文件对话框,用户可以保存该文件或者取消,并且对话框能知道文件类型。
...全文
170 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
正在找呵呵
伍子V5 2007-10-11
  • 打赏
  • 举报
回复
类似这样


public ActionForward download(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("entering 'AttachmentAction.download()' method...");
}
ActionMessages messages = new ActionMessages();

String id = request.getParameter("id");
String attachmentFile=request.getParameter("file");
String type = request.getParameter("type");
if (id != null||attachmentFile!=null) {
Attachment attachment =null;
if(id!=null) {
attachment= mgr.view(id);
} else if(attachmentFile!=null) {
attachment=mgr.viewByFile(attachmentFile);
}

if (attachment == null) {
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"object.miss"));
saveMessages(request, messages);
return mapping.findForward("failure");
}
//filename=new String(filename.getBytes("iso-8859-1"),"gb2312");
//String filepath=this.getServletContext().getRealPath("/upload");
File file = new File(mgr.getRoot()+"/"+attachment.getAttachmentFile());
String fileName = URLEncoder.encode(attachment.getAttachment(),
"UTF-8");
BufferedInputStream br = new BufferedInputStream(
new FileInputStream(file));
byte[] buf = new byte[1024 * 1024];
int len = 0;
response.reset(); //纯下载方式
//response.setContentType("application/x-msdownload");
if (type == null) {
response
.setContentType("application/octet-stream;charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition",
"attachment; filename=" + fileName);
} else if (type != null && type.equals("jpg")) {
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
return null;
}
For_suzhen 2007-10-11
  • 打赏
  • 举报
回复
直接用java的读写流类就可以了,读取文件写到response里面,frush一下就直接弹出文件保存的对话框了,这是浏览器自带的。有一个参数就是设置文件名的,不仅仅是扩展名,全名都有
kokolodo 2007-10-11
  • 打赏
  • 举报
回复
嗯,可以用第三方jar包,就是楼上说的SmartUpLoad就可以了!
liu_shui8 2007-10-11
  • 打赏
  • 举报
回复
有个第三方Bean让你用:jspsmart;
xiyuan1999 2007-10-11
  • 打赏
  • 举报
回复
SmartUpLoad就可以了

或者cos

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧