您的位置:首页 > 其它

response实现文件下载

2014-09-09 22:32 295 查看
假设web目录下有一个文件



程序如下

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"));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: