Servlet 文件下载提示保存文件 Content-Disposition :attachment和inline的区别

有些话、适合烂在心里 提交于 2020-01-27 22:23:01

Servlet 文件下载提示保存文件 Content-Disposition :attachment和inline的区别

前端页面:

<body>

<!-- 无设置默认打开 inline -->
<a href="img/美女.jpg"><img src="img/美女.jpg"  >图片1</a><br/>
<a href="mp4/01.课程内容简介.mp4">视频</a>
<hr/>

<!-- attachment -->
<a href="DownloadServlet2?filename=美女.jpg">图片1 点击下载</a><br/>
<a href="DownloadServlet2?filename=01.课程内容简介.mp4">视频  点击下载</a>


@WebServlet("/DownloadServlet2")
public class DownloadServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String filename = request.getParameter("filename");
        String suffix = filename.substring(filename.lastIndexOf(".")+1);
        String path = null;
        if(suffix.equals("jpg")){
            path = getServletContext().getRealPath("img");
        }else if (suffix.equals("mp4")){
            path = getServletContext().getRealPath("mp4");
        }
        if(path != null){
            FileInputStream fis = new FileInputStream(path + "/" + filename);
            response.setHeader("content-disposition","attachment; filename="+DownloadUtils.encodeFilename(request,filename));

            ServletOutputStream sos = response.getOutputStream();
            byte[] lens = new byte[8192];
            int len;
            while((len = fis.read(lens))!= -1){
                sos.write(lens,0,len);
            }
            sos.close();
            fis.close();
        }
    }
public class DownloadUtils {
	/**
	 * 解决下载时,中文文件名称乱码问题<br>
	 * 
	 * @param request request对象
	 * @param filename 你想让用户保存的文件名称
	 */
	public static String encodeFilename(HttpServletRequest request, String filename){ 
		try{
			String agent = request.getHeader("User-Agent");
			if (agent.contains("MSIE")) {
				// IE浏览器
				filename = URLEncoder.encode(filename, "utf-8");
				filename = filename.replace("+", " ");
			} else if (agent.contains("Firefox")) {
				// 火狐浏览器
				//BASE64Encoder base64Encoder = new BASE64Encoder();
				Base64.Encoder base64Encoder = Base64.getEncoder();
				filename = base64Encoder.encodeToString(filename.getBytes("utf-8"));
				filename = "=?utf-8?B?"+ filename + "?=";
			} else {
				// 其它浏览器
				filename = URLEncoder.encode(filename, "utf-8");				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return filename;
	}
}

在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!