response实现文件下载

假设web目录下有一个文件

response实现文件下载_第1张图片

程序如下

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String path = this.getServletContext().getRealPath("/download/1.jpg");
		String filename = path.substring(path.lastIndexOf("\\")+1);
		
		response.setHeader("content-disposition", "attachment;filename"+filename);
		
		InputStream in = null;
		OutputStream out = null;
		
		try{
			in = new FileInputStream(path);
			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();
				}
			}
			if(out!=null){
				try{
					in.close();
				}catch (Exception e){
					e.printStackTrace();
				}
			}
		}
	}

如果文件名是中文要用url编码,改为

response.setHeader("content-disposition", "attachment;filename"+URLEncoder.encode(filename,"utf-8"));

你可能感兴趣的:(servlet)