servlet 下载文件 以及 下载文件名字 中文乱码 解决 处理

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadClient extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		download(request,response);
	}
	
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
        	// UploadConfigConstants.CLIENT_FILE是下载文件的路径。
        	File file = new File(request.getSession().getServletContext().getRealPath(UploadConfigConstants.CLIENT_FILE));
        	if(! file.getParentFile().exists()){
        		file.getParentFile().mkdirs();
        	}
        	if(! file.exists()){
        		file.createNewFile();
        	}
        	 // 清空response
            response.reset();
            // 设置response的Header,同时解决乱码问题
        	response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("GBK"),"ISO8859_1"));
            response.addHeader("Content-Length", "" + file.length());
            // 以流的形式下载文件。
            response.setContentType("application/octet-stream");
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            byte[] b = new byte[2048];
            int n = -1;
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            while((n = in.read(b)) != -1){
            	out.write(b,0,n);
            }
            in.close();
            out.flush();
            out.close();
        } catch (IOException ex) {
           throw ex;
        }
    }

}

 

你可能感兴趣的:(servlet)