zoukankan      html  css  js  c++  java
  • 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);
    	}
    
    }
    
  • 相关阅读:
    c#中跨线程调用windows窗体控件
    像职业选手样编码:地道Python
    数据挖掘笔记 第一章:引言
    SVN使用教程(基于SAE)
    常用的js函数
    linux服务之tuned
    PHP 开启短标签
    如叶梦想!
    分布式控制系统Git学习
    LabVIEW(十六):多列列表框控件
  • 原文地址:https://www.cnblogs.com/amosli/p/3318300.html
Copyright © 2011-2022 走看看