美文网首页程序员
Servlet文件下载(中文名称乱码)

Servlet文件下载(中文名称乱码)

作者: 干自闭 | 来源:发表于2020-08-24 11:15 被阅读0次

首先确定HTML页面上的编码格式 我这里是UTF-8

<meta http-equiv="content-type" content="text/html;charset=utf-8">
  • 创建类继承HttpServlet ;
  • 重写doGet或doPost,具体使用哪个看业务需求;
    代码如下:
import sun.misc.BASE64Encoder;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author: GanZiB
 * Date: 2020-08-24
 * Time: 10:16
 */
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.获取文件名
        String fileName = req.getParameter("fileName");
        //2.使用字节输入流加载文件进内存
        //2.1找到文件服务器路径
        ServletContext servletContext = req.getServletContext();
        String realPath = servletContext.getRealPath("/res/" + fileName);
        //2.2使用字节流关联
        FileInputStream fis = new FileInputStream(realPath);
        //3.设置response响应头
        //3.1设置响应头类型:content-type
        String agent = req.getHeader("user-agent");
        String mimeType = servletContext.getMimeType(fileName);
        resp.setHeader("content-type", mimeType);
        //3.2设置响应头打开方式:content-disposition
        resp.setHeader("content-disposition", "attachment;filename=" + getFileName(agent,fileName));
        //4.将输入流数据写出到输出流中
        ServletOutputStream sos = resp.getOutputStream();
        byte[] buff = new byte[1024 * 8];
        int len = 0;
        while ((len = fis.read(buff)) != -1) {
            sos.write(buff, 0, len);
        }
        fis.close();
    }

    /**
      * 中文乱码适配不同浏览器
      */
    public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
        if (agent.contains("MSIE")) {
            // IE
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            //火狐
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes(StandardCharsets.UTF_8)) + "?=";
        }else {
            filename = URLEncoder.encode(filename,"utf-8");
        }
        return filename;
    }
}
<html>
<head>
    <meta charset="UTF-8">
</head>

<body>

<a href="/download?fileName=图片1.jpg">图片下载</a>
</body>

</html>

相关文章

网友评论

    本文标题:Servlet文件下载(中文名称乱码)

    本文链接:https://www.haomeiwen.com/subject/giwgjktx.html