jsp页面:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="DownloadServlet?urlStr=index.jsp">下载index.jsp</a>
<a href="DownloadServlet?urlStr=photo/1.jpg">下载1.jpg</a>
<a href="DownloadServlet?urlStr=test.jsp">下载test.jsp</a>
</body>
</html>
Servlet:
package org.jimmy.testwebproject2019012602.servlet.download; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author Yang.Yuxin(Jimmy) * @date 2019年2月14日 下午5:39:47 * @detail 下载Servlet */ public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String urlStr = request.getParameter("urlStr"); String fileName = urlStr.substring(urlStr.lastIndexOf("/") + 1); response.setContentType("application/x-msdownload; charset=utf-8"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); //这个是使用项目的相对路径来获取文件的输入流 InputStream is = request.getServletContext().getResourceAsStream(urlStr); /* //这个可以使用绝对路径来获取文件的输入流 FileInputStream fis = new FileInputStream("D:\\Document\\201902\\20190228\\Test\\1.jpg"); */ ServletOutputStream sos = response.getOutputStream(); int fileLength = is.available(); int cacheLength = 1024; if(fileLength < cacheLength) { cacheLength = fileLength; } int len = cacheLength; byte[] bytes = new byte[cacheLength]; while((len = is.read(bytes, 0, len)) != -1) { sos.write(bytes); } sos.flush(); sos.close(); is.close(); }catch(Exception e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
原文:https://www.cnblogs.com/JimmySeraph/p/10449017.html