Requirements: Implement a web page with file download function, mainly downloading compressed packages and pictures:
1: Download through hyperlink
In an HTML page, link to the address of the file to be downloaded via a hyperlink
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>Download file through link</h1> <a href="/day06/download/cors.zip">Compression package</a> <a href="/day06/download/1.png">Picture</a> </body> </html>
where day06/download is the document path, the program structure of this example is as follows:
After the program is run, you can download it by clicking on the document you need to download.
But a problem will appear here, that is, when you click to download the compressed package, the download page will pop up, but when you download the picture, the browser will directly open the picture and there is no download.
This is because when downloading a file through a hyperlink, if the browser can recognize the file format, the browser will open directly. Downloading will only be achieved if the browser cannot recognize the file format. Therefore, the second method is used to realize the download function.
2: Implement download through Servlet program
The principle of downloading files through Servlet is to read the target program through servlet and return the resources to the client.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>Download file through link</h1> <a href="/day06/download/cors.zip">Compression package</a> <a href="/day06/download/1.png">Picture</a> <h1>Download file through servlet program</h1> <a href="/day06/ServletDownload?filename=cors.zip">Compression package</a> <a href="/day06/ServletDownload?filename=1.png">Picture</a> </body> </html>
Where /day06/ServletDownload is the mapping path of the servlet program and then create a new servlet, name ServletDownload, and the URL is mapped to /ServletDownload.
Add the code as follows:
package com.lsgjzhuwei.servlet.response; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ServletDownload */ @WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" }) public class ServletDownload extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ServletDownload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //Get the request file name String filename = request.getParameter("filename"); System.out.println(filename); //Set the file MIME type response.setContentType(getServletContext().getMimeType(filename)); //Set Content-Disposition response.setHeader("Content-Disposition", "attachment;filename="+filename); //Read the target file and write the target file to the client through response//Get the absolute path of the target file String fullFileName = getServletContext().getRealPath("/download/" + filename); //System.out.println(fullFileName); //Read file InputStream in = new FileInputStream(fullFileName); OutputStream out = response.getOutputStream(); //Write file int b; while((b=in.read())!= -1) { out.write(b); } in.close(); out.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } } Restart the tomcat server to realize the download of compressed packages and pictures.
Three. Tips:
The way to download files is very simple to click on the link. The background outputs the file stream and realizes the download function through the browser, including inquiring about location and file storage. Most browsers will configure a fixed location, and may not ask every time.
The front-end is very simple, with a <a> tag, href="backend method address". If your needs cannot be directly used in hyperlink mode, you can write window.location.href="backend method address" in js.
After jumping to the background method
String filePath = this.getClass().getClassLoader().getResource("").toURI().getPath() + "/exportPdf.pdf"; //Path of the file in the project File outfile = new File(filePath); String filename = outfile.getName();//Get the file name InputStream fis = new BufferedInputStream(new FileInputStream(filePath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); //Read file stream fis.close(); response.reset(); //Reset the result set response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1")); //Return the header file name response.addHeader("Content-Length", "" + outfile.length()); //Return the header file size response.setContentType("application/octet-stream"); //Set the data type//Get the return body output right OutputStream os = new BufferedOutputStream(response.getOutputStream()); os.write(buffer); // Output file os.flush(); os.close(); The browser will directly recognize this form of file output and a dialog box pops up.
Note that this method must be adjusted in the background using link method. It is not possible to use ajax and XMLHttpRequest methods. In this way, the returned file stream will be returned to the method's callback function. Of course, if you want to get the file in js, this will work.