package cn.itcast.web.download; import javax.servlet.ServletContext; import javax.servlet.ServletException; 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.FileOutputStream; import java.io.IOException; @WebServlet("/DownloadServlet_Demo1") public class DownloadServlet_Demo1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("filename"); ServletContext servletContext = this.getServletContext(); String mimeType = servletContext.getMimeType(filename); response.setHeader("content-type",mimeType); response.setHeader("content-disposition","attachment;filename="+filename); String realPath = servletContext.getRealPath("/img/" + filename); FileInputStream fileInputStream = new FileInputStream(realPath); ServletOutputStream outputStream = response.getOutputStream(); byte[] bytes = new byte[1024 * 5]; int len=0; while ((len=fileInputStream.read(bytes))!=-1){ outputStream.write(bytes,0,len); } fileInputStream.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } } <a href="/DownloadServlet_Demo1?filename=a.png">云同桌</a>