在Servlet中以下载的方式向浏览器写数据--中文文件乱码问题解决

IT程序员开发必备-各类资源下载清单,史上最全IT资源,个人收藏总结!



例子程序:

package edu.response;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//以下载的方式向浏览器写数据
public class FileDownloadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        String path = this.getServletContext().getRealPath("/download/美女1.jpg");
        String filename = path.substring(path.lastIndexOf("\\")+1);
        //如果是下载中文文件需要url编码,否则下载文件正常,但文件名乱码
        response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));
        InputStream in = null;
        OutputStream out = null;
        try{
	        in = new FileInputStream(path);
	        out = response.getOutputStream();
	        int len = 0;
	        byte buffer[] = new byte[1024];
	        while((len=in.read(buffer))>0){
	        	out.write(buffer,0,len);
	        }
        }finally{
        	if(in!=null){
        		in.close();
        	}
        	if (out!=null) {
				out.close();
			}
        	
        }    
        
        
        System.out.println(filename);
	}

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

}


你可能感兴趣的:(在Servlet中以下载的方式向浏览器写数据--中文文件乱码问题解决)