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

Servlet实现文件下载

程序员文章站 2022-05-24 20:51:09
...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	(图片)<a href="/day03/download?filename=r1.jpg">下载</a><br/>
</body>
</html>
<servlet>
    <description></description>
    <display-name>UploadFile</display-name>
    <servlet-name>UploadFile</servlet-name>
    <servlet-class>xinfei.code.file.UploadFile</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadFile</servlet-name>
    <url-pattern>/uploadFile</url-pattern>
  </servlet-mapping>
public class UploadFile extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取要下载的问价名称
		String filename = request.getParameter("filename");
		//获取上下文对象
		ServletContext context = getServletContext();
		//获取要下载文件的类型
		String mimeType = context.getMimeType(filename);
		//设置文件下载头
		String agent = request.getHeader("user-agent");
		//如果是中文可能会有编码问题  这里会使用一个工具类
		String f_name = new Date().toString();
		f_name = DownLoadUtils.getName(agent, f_name);
		response.setHeader("content-disposition", "attachment;filename="+f_name+".jpg");
		
		//设置流
		ServletOutputStream os = response.getOutputStream();
		InputStream is = context.getResourceAsStream("/download/"+filename);
		IOUtils.copy(is, os);
		//关流
		is.close();
		os.close();
	}

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

编码工具类

public class DownLoadUtils {
	public static String getName(String agent, String filename) throws UnsupportedEncodingException {
		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;
	}
}