今天学习了JavaWeb实现文件下载,为了以后方便查找并让需要的人学习,今儿把代码献上!!!!
大笑
首先写一个jsp页面
字体加粗的为主要内容:
download.jsp:
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
然后在定义一个Servlet,如下:
DownloadServlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
//设置ContentType字段值
response.setContentType("text/html;charset=utf-8");
//获取所要下载的文件名称
String filename = request.getParameter("filename");
//下载文件所在目录
String folder = "/filename/";
//通知浏览器以下载的方式打开
response.addHeader("Content-type", "appllication/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename="+filename);
//通知文件流读取文件
InputStream in = getServletContext().getResourceAsStream(folder+filename);
//获取response对象的输出流
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
//循环取出流中的数据
while((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
}
用到的架包:commons-fileupload-1.3.1.jar、commons-io-2.4.jar