File upload is very common in web applications. It is very easy to implement file upload function in Java Web environment, because there are already many components developed in Java for file upload on the Internet. This article uses the most commons-fileupload component as an example to demonstrate how to add file upload function to Java Web applications.
The commons-fileupload component is one of Apache's open source projects and can be downloaded from http://commons.apache.org/fileupload/. This component is simple and easy to use, allowing you to upload one or more files at a time and can limit file size.
After downloading, unzip the zip package and copy commons-fileupload-1.x.jar to tomcat's webapps/your webapp/WEB-INF/lib/. If the directory does not exist, please create your own directory.
Create a new UploadServlet.java for file upload:
package com.liaoxuefeng.web;public class FileUploadServlet extends HttpServlet { private String uploadDir = "C://temp"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO: }}When the servlet receives the Post request issued by the browser, it implements file upload in the doPost() method. We need to traverse the FileItemIterator and get each FileItemStream:
@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ try { ServletFileUpload upload = new ServletFileUpload(); // set max file size to 1 MB: upload.setFileSizeMax(1024 * 1024); FileItemIterator it = upload.getItemIterator(req); // handle with each file: while (it.hasNext()) { FileItemStream item = it.next(); if (! item.isFormField()) { // it is a file upload: handleFileItem(item); } } req.getRequestDispatcher("success.jsp").forward(req, resp); } catch(FileUploadException e) { throw new ServletException("Cannot upload file.", e); }}Read the input stream of uploaded files in the handleFileItem() method, and then write it to uploadDir, and the file name is randomly generated by UUID:
void handleFileItem(FileItemStream item) throws IOException { System.out.println("upload file: " + item.getName()); File newUploadFile = new File(uploadDir + "/" + UUID.randomUUID().toString()); byte[] buffer = new byte[4096]; InputStream input = null; OutputStream output = null; try { input = item.openStream(); output = new BufferedOutputStream(new FileOutputStream(newUploadFile)); for (;;) { int n = input.read(buffer); if (n==(-1)) break; output.write(buffer, 0, n); } } finally { if (input!=null) { try { input.close(); } catch (IOException e) {} }}If you want to read the specified upload folder in the web.xml configuration file, you can initialize it in the init() method:
@Overridepublic void init(ServletConfig config) throws ServletException { super.init(config); this.uploaddir = config.getInitParameter("dir");}Finally, configure the Servlet in web.xml:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.liaoxuefeng.web.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/upload</url-pattern> </servlet-mapping></web-app>
After configuring the Servlet, start Tomcat or Resin and write a simple index.htm test:
<html><body><p>FileUploadServlet Demo</p><form name="form1" action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" name="button" value="Submit" /></form></body></html>
Note that action="upload" specifies the mapping URL of the FileUploadServlet that handles uploaded files.
When the upload is successful, success.jsp is displayed, otherwise, an exception is thrown. If the uploaded file size exceeds 1MB we set, we will get a FileSizeLimitExceededException.
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.