This article shares the specific code for Servlet file download for your reference. The specific content is as follows
It is not safe to expose the file directory directly to the user. So you have to use servlets, and in this way, the files will be stored more abundantly. They can be retrieved from the file system, generated by calculations in the database, or retrieved from other strange places.
public class DownloadServlet extends HttpServlet { private String contentType = "application/x-msdownload"; private String enc = "utf-8"; private String fileRoot = ""; /** * Initialize contentType, enc, fileRoot */ public void init(ServletConfig config) throws ServletException { String tempStr = config.getInitParameter("contentType"); if (tempStr != null && !tempStr.equals("")) { contentType = tempStr; } tempStr = config.getInitParameter("enc"); if (tempStr != null && !tempStr.equals("")) { enc = tempStr; } tempStr = config.getInitParameter("fileRoot"); if (tempStr != null && !tempStr.equals("")) { fileRoot = tempStr; } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filepath = request.getParameter("filepath"); String fullFilePath = fileRoot + filepath; /*Read file*/ File file = new File(fullFilePath); /*If the file exists*/ if (file.exists()) { String filename = URLEncoder.encode(file.getName(), enc); response.reset(); response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=/"" + filename + "/""); int fileLength = (int) file.length(); response.setContentLength(fileLength); /*If the file length is greater than 0*/ if (fileLength != 0) { /*Create input stream*/ InputStream inStream = new FileInputStream(file); byte[] buf = new byte[4096]; /*Create output stream*/ ServletOutputStream servletOS = response.getOutputStream(); int readLength; while (((readLength = inStream.read(buf)) != -1)) { servletOS.write(buf, 0, readLength); } inStream.close(); servletOS.flush(); servletOS.close(); } } } web.xml
<servlet> <servlet-name>downloadservlet-name> <servlet-class>org.mstar.servlet.DownloadServletservlet-class> <init-param> <param-name>fileRootparam-name> <param-value>d:/tempparam-value>init-param> <init-param> <param-name>contentTypeparam-name> <param-value>application/x-msdownloadparam-value>init-param> <init-param> <param-name>encparam-name> <param-value>utf-8param-value>>> init-param> servlet> <servlet-mapping> <servlet-name>downloadservlet-name> <url-pattern>/downurl-pattern> servlet-mapping>
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.