下载文件

 

public class DownloadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		OutputStream out = null;
		InputStream in = null;
		
		String fileName = request.getParameter("fileName");
		if(fileName == null){
			out = response.getOutputStream();
			out.write("请输入文件名!".getBytes());
			out.close();
			return;
		}
		
		in = this.getServletContext().getResourceAsStream("/file/" + fileName);	
		int len = in.available();
		response.setContentType("application/force-download");
		response.setHeader("Content-Lenght", String.valueOf(len));
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		out = response.getOutputStream();
		int readByte = 0;
		byte buf[] = new byte[1024];
		while((readByte = in.read(buf))!= -1){
			out.write(buf, 0, readByte);
		}
		in.close();
		out.close();
		
	}

}

你可能感兴趣的:(下载文件)