JSP文件下载超简单方法,只需要一个apach包
找了N多的下载方法,这个个人感觉是最方便的,传入两个参数,全路径和文件名,也可以只传路径,文件在方法中获取。哈哈 ,好东西分享一下。
import org.apache.commons.net.io.Util;
public ActionForward down(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String fullpath = request.getParameter("fullpath").trim(); // 文件的全路径
String fileName =request.getParameter("filename").trim();
InputStream in = null;
try {
in = new FileInputStream(fullpath);
System.out.print(" read success");
response.reset();// 必须重新设置,否则在第一次下载取消后,再下载会报response.getOutputStream()重复调用。
response.setContentType("application/x-pn-realmedia");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
System.out.print("copy start");
Util.copyStream(in, response.getOutputStream());
} catch (FileNotFoundException e) {
e.printStackTrace();
request.setAttribute("message", "文件不存在");
return mapping.findForward("fail");
} catch (IOException e) {
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}