There are two types of web file downloads. One is that the file is in the website directory. You can download it by directly entering the file path in the browser, such as http://www.xxx.com/file.zip. Another type is that the file is not in the website directory or the file is generated dynamically (export reports or export excel, etc.). In this case, the file download needs to be achieved through the OutputStream of the response. DownloadUtils is a Java Web file download tool class that provides a variety of static methods to implement file download.
package com.rhui.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; /** * File download class*/ public class DownloadUtils { /** * File download encoding* This encoding tells the browser the encoding method of the file name to prevent garbled code when downloading Chinese file names*/ private static String encoding = "utf-8"; /** * File download* @param response * @param filePath The path of the file on the server, including the file name*/ public static void download(HttpServletResponse response, String filePath){ File file = new File(filePath.toString()); download(response, file, null, encoding); } /** * File download* @param response * @param filePath The path of the file on the server, including the file name* @param fileName The name of the file downloaded to the browser. If you do not want the name of the file downloaded by the browser to the same as the file name on the server, please set this parameter */ public static void download(HttpServletResponse response, String filePath, String fileName){ File file = new File(filePath.toString()); download(response, file, fileName, encoding); } /** * File download* @param response * @param filePath The path of the file on the server, including the file name* @param fileName The name of the file downloaded to the browser. If you do not want the file name downloaded by the browser to the same as the file name on the server, please set this parameter* @param encoding File name encoding*/ public static void download(HttpServletResponse response, String filePath, String fileName, String encoding){ File file = new File(filePath.toString()); download(response, file, fileName, encoding); } /** * File download* @param response * @param file file * @param fileName The name of the downloaded file to the browser. If you do not want the file name downloaded by the browser to the same as the file name on the server, please set this parameter */ public static void download(HttpServletResponse response, File file) { download(response, file, null, encoding); } /** * File download* @param response * @param file file* @param fileName The name of the downloaded file to the browser. If you do not want the file name downloaded by the browser to the same as the file name on the server, please set this parameter */ public static void download(HttpServletResponse response, File file, String fileName) { download(response, file, fileName, encoding); } /** * File download* @param response * @param file file* @param fileName The name of the downloaded file to the browser. If you do not want the file name downloaded by the browser to the same as the file name on the server, please set this parameter* @param encoding File name encoding*/ public static void download(HttpServletResponse response, File file, String fileName, String encoding) { if(file == null || !file.exists() || file.isDirectory()){ return; } // If you do not specify the name of the file to download to the browser, use the default name of the file if (StringUtils.isBlank(fileName)) { fileName = file.getName(); } try { InputStream is = new FileInputStream(file); download(response, is, fileName, encoding); } catch (IOException e) { e.printStackTrace(); } } /** * File download* @param response * @param is file input stream* @param fileName Downloaded file name* @throws IOException */ public static void download(HttpServletResponse response, InputStream is, String fileName){ download(response, is, fileName, encoding); } /** * File download* @param response * @param is file input stream* @param fileName Downloaded file name* @param encoding Encoding format*/ public static void download(HttpServletResponse response, InputStream is, String fileName, String encoding){ if(is == null || StringUtils.isBlank(fileName)){ return; } BufferedInputStream bis = null; OutputStream os = null; BufferedOutputStream bos = null; try{ bis = new BufferedInputStream(is); os = response.getOutputStream(); bos = new BufferedOutputStream(os); response.setContentType("application/octet-stream;charset=" + encoding); response.setCharacterEncoding(encoding); response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, encoding)); byte[] buffer = new byte[1024]; int len = bis.read(buffer); while(len != -1){ bos.write(buffer, 0, len); len = bis.read(buffer); } bos.flush(); } catch(IOException e){ e.printStackTrace(); } finally{ if(bis != null){ try{ bis.close(); }catch(IOException e){} } if(is != null){ try{ is.close(); }catch(IOException e){} } } } public static String getEncoding() { return encoding; } public static void setEncoding(String encoding) { DownloadUtils.encoding = encoding; } }If the file is saved in a non-site directory on the server
String filePath = "c://file.zip"; DownloadUtils.download(response, filePath);
If the file is an input stream
// is the file input stream// fileName is the file name downloaded by the browser// encoding is the file name to prevent garbled codes when there is Chinese in the file String fileName = "file.zip"; String encoding = "utf-8"; DownloadUtils.download(response, is, fileName, encoding);
Download files in servlet
package com.rhui.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.rhui.util.DownloadUtils; @WebServlet("/download/servlet") public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = "c://file.zip"; DownloadUtils.download(response, filePath); } } PS: Picture download (including anti-theft link function)
package cn.itcast.day06.web.servlet; import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URLEncoder; import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Implement anti-theft chain function// Get the referer header to explain where the visitor comes from String referer = request.getHeader("referer"); if(referer==null || !referer.startsWith("http://localhost")) { // It is a link thief response.sendRedirect("/day06/index.jsp"); return ; } // Solve the problem of response Chinese garbled response response.setContentType("text/html;charset=utf-8"); // Set the encoding of the message body // The http response message header sent through the http protocol cannot appear in Chinese Chinese, Chinese must be url-encoded String filename = URLEncoder.encode("Beauty.jpg", "utf-8"); // Notify the browser to read the resource response.setHeader("content-disposition", "attachment;filename="+filename); // Read the image data and send it to the ie browser String webPath = "/download/Beauty.jpg"; // equivalent to the path of the current web application ServletContext servletContext = super.getServletContext(); InputStream in = servletContext.getResourceAsStream(webPath); OutputStream out = response.getOutputStream(); int len; byte[] buffer = new byte[1024]; while((len=in.read(buffer))!=-1) out.write(buffer, 0, len); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }