Java web response provides the file download function, response File Download
The structure of a webapp project is as follows:
The content of the download.html file is as follows:
<! DOCTYPE html>
The content of the Servlet-download. java file responsible for processing the download is as follows:
Package com. download. servlet; 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;/*** Servlet implementation class Download */public class Download extends Htt PServlet {private static final long serialVersionUID = 1L; protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 1. obtain the file name String filename = request. getParameter ("filename"); // 2. obtain the file system path String filePath = request. getServletContext (). getRealPath ("resource/" + filename); // 3. set the response header, prompting the browser not to parse the response file data, but to parse it in the form of an attachment (attachment), that is, the download function re Else se. setContentType (this. getServletContext (). getMimeType (filename); response. setHeader ("Content-Disposition", "attachment; filename =" + filename); // 4. read the input stream of the file and the output stream of the response, and output the data to the client InputStream in = new FileInputStream (filePath); ServletOutputStream out = response. getOutputStream (); int len = 0; byte [] buf = new byte [1024]; while (len = in. read (buf ))! =-1) {out. write (buf, 0, len);} in. close ();} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
In the browser address bar, enterhttp://localhost:8080/DownloadServlet/download.html
.
Note: If you think this article is not bad, please click the recommendation in the lower right corner. Your support can stimulate the author's enthusiasm for writing. Thank you very much!