欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javaWeb 文件下载乱码问题解决方案

程序员文章站 2022-03-19 18:35:38
...

解决问题:下载文件乱码问题

    package cn.yellowimg.web.servlet;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;

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

    import org.apache.commons.io.IOUtils;

    public class Dowmload1Servlet extends HttpServlet {


    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        /*
         * 准备两个头一个流
         * 两头:
         * 1 Content-Type
         * 2 Content-Disposition
         * 3 流 下载文件数据
         */
        String fileName = "D:/高圆圆.jpg";
        //获取mime类型
        String contentType =  req.getServletContext().getMimeType(fileName);

        FileInputStream fileInputStream = new FileInputStream(fileName);

        //调用filenameEncoding()方法是为了防止文件乱码
        //也可以使用new String(fileName.getByte("GBK"),"ISO-8859-1");

        String contentDisposition = "attachment;filename="+DownUtils .filenameEncoding(fileName,req);

        resp.setHeader("Content-Type", contentType);

        resp.setHeader("Content-Disposition", contentDisposition);

        //获取绑定客户端输出的流
        ServletOutputStream servletOutputStream = resp.getOutputStream();

        IOUtils.copy(fileInputStream, servletOutputStream);

        fileInputStream.close();
        }
    }

package cn.itcast.down.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import sun.misc.BASE64Encoder;

public class DownUtils {
    public static String filenameEncoding(String filename, HttpServletRequest request) throws IOException {
        String agent = request.getHeader("User-Agent"); //获取浏览器
        if (agent.contains("Firefox")) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?"
                    + base64Encoder.encode(filename.getBytes("utf-8"))
                    + "?=";
        } else if(agent.contains("MSIE")) {
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }
}