Servlet文件下載(中文名稱亂碼)

首先確定HTML頁面上的編碼格式 我這里是UTF-8

<meta http-equiv="content-type" content="text/html;charset=utf-8">
  • 創(chuàng)建類繼承HttpServlet ;
  • 重寫doGet或doPost,具體使用哪個看業(yè)務需求;
    代碼如下:
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.使用字節(jié)輸入流加載文件進內(nèi)存
        //2.1找到文件服務器路徑
        ServletContext servletContext = req.getServletContext();
        String realPath = servletContext.getRealPath("/res/" + fileName);
        //2.2使用字節(jié)流關聯(lián)
        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.將輸入流數(shù)據(jù)寫出到輸出流中
        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>
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容