servlet 中通过response下载文件

public class ResponseDemo3 extends HttpServlet {
	private static final long serialVersionUID = -5232952995715123473L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// ServletOutputStream outputStream = response.getOutputStream();
		// outputStream.write("hello,download!".getBytes());
		String realPath = this.getServletContext().getRealPath("/download/日本妞.jpg");
		String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
		//如果下载文件是中文文件,则文件名需要经过url编码
		response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));
		InputStream in = null;
		OutputStream out = null;
		try{
		in = new FileInputStream(realPath);
		int len = 0;
		byte buffer[] = new byte[1024];
		out = response.getOutputStream();
		while((len=in.read(buffer))>0){
			out.write(buffer,0,len);
		}
	
		}finally{
			if(in!=null){
				try{
					in.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 

你可能感兴趣的:(response)