Servlet notes-ServletContext and file download

ServletContext

  1. Concept: represents the context of the entire web application

  2. Features

    1. Get MIME type

      1. MIME: File data type defined during Internet communication

        1. Format: large type/small type

          such as text/html image/jpeg

      2. Obtain:String getMimeType(String file)

    2. As a domain object, share data

      1. getAttribute(String name,Object value)
      2. setAttribute(String name,Object value)
      3. removeAttribute(String name)

      The scope of ServletContext: the entire web application

    3. Get the real path of the file (server path)

      1. String getRealPath(String path)

      Can be used to load a file in the project in the program (usually a configuration file)

  3. Obtain

    1. Get through the request object

      request.getServletContext();
      
    2. Get through HttpServlet

      //在一个HttpServlet类中
      this.getServletContext();
      

Case: File download

  1. Page displays hyperlinks
  2. After clicking the hyperlink, a download prompt box will pop up
  3. Complete file download

analysis:

  1. If the resource pointed to by the hyperlink can be parsed by the browser, such as a picture, it will be displayed in the browser directly, and the download will be prompted for those that cannot be parsed by the browser. So directly use hyperlinks to point to resource files, which does not meet the demand
  2. Use response headers, setContent-disposition:attachment;filename=xx

Implementation steps:

  1. Edit the hyperlink, let its href point to a servlet, and pass the resource name
  2. Write Servlet
    1. Get file name
    2. Find the corresponding file and load it into the memory using the byte input stream
    3. Specify the response headerContent-disposition
    4. Write data to the response output stream

Code display:

html page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!-- 浏览器能展示的资源,会直接展示 -->
    <a href="/download?filename=达不溜.jpeg">AW</a>
    <br>
    <!-- 像视频这样,浏览器无法解析
    经测试,IE浏览器中,点击此超链接,会提示下载mp4文件
    Chrome中,点击超链接,会直接打开mp4文件,在Chrome中直接播放
    -->
    <a href="/download?filename=my_first_vlog.mp4">vlog</a>
</body>
</html>

The resource files are placed in the /web/resources directory
Insert picture description here

Servlet processing logic

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		doGet(request,response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

		ServletContext context = getServletContext();
		//获取文件,加载到内存中
		request.setCharacterEncoding("utf-8");
		String filename = request.getParameter("filename");
		//给文件名添加路径 /resources  ,默认把资源文件都放resources下
		filename = "/resources/" + filename;
		//获取文件真实路径
		String path = context.getRealPath(filename);
		FileInputStream inputStream = new FileInputStream(path);

		//设置response的响应头,设置content-type和content-disposition
		//表明响应体中的数据是什么MIME类型
		response.setContentType(context.getMimeType(filename));
		//表明以附件形式下载响应体数据

		//解决中文文件名问题
		// 1. 获取user-agent请求头
		// 2. 使用DownloadUtil工具类编码文件名
		String userAgent = request.getHeader("user-agent");
		filename = DownloadUtil.getFileName(userAgent,filename);

		response.setHeader("content-disposition","attachment;filename="+filename);


		//输出到response的流
		ServletOutputStream outputStream = response.getOutputStream();
		byte[] bytes = new byte[1024];
		int len = 0;
		while ((len = inputStream.read(bytes)) != -1){
    
    
			outputStream.write(bytes);
		}

		inputStream.close();
	}
}

Among them, DownloadUtil is used to solve the situation that different browsers are not friendly to Chinese file name support

import sun.misc.BASE64Encoder;

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

/**
 * 下载工具类
 * 用于解决下载时显示的中文文件名称的问题
 * */
public class DownloadUtil {
    
    
	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("utf-8")) + "?=";
		}else {
    
    
			//其他浏览器
			filename = URLEncoder.encode(filename,"utf-8");
		}
		return filename;
	}
}

Show results
Insert picture description here

Guess you like

Origin blog.csdn.net/vcj1009784814/article/details/106083916