There are currently two commonly used methods for file uploading, one is SmartUpload and the other is Apache's Commons fileupload .
Here we mainly introduce the usage of the second one. First, you need to upload the file and pay attention to several issues:
1 In the form form, add space <input type="file" name="myfile">
2 The content format of the form form should be defined as multipart/form-data format
3 Required class library: 1 commons-io.jar 2 commons-fileupload-1.3.1.jar
Next, let’s take a look at the usage.
First, read the official documentation of Apache commons fileupload and you can find the following commonly used functions:
1 Create a file parsing object
The code copy is as follows: DiskFileUpload diskFileUpload = new DiskFileUpload();
2 After parsing the file, put it in the List. Because this class library supports multiple files uploads, the result will be stored in the List.
The code copy is as follows: List<FileItem> list = diskFileUpload.parseRequest(request);
3 Get uploaded files and perform analysis (not necessary)
The code copy is as follows: File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
4 Create a new object and perform streaming copy
file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName()); file1.getParentFile().mkdirs(); file1.createNewFile(); InputStream ins = fileItem.getInputStream(); OutputStream ous = new FileOutputStream(file1); try{ byte[] buffer = new byte[1024]; int len = 0; while((len = ins.read(buffer)) > -1) ous.write(buffer,0,len); out.println("to save file"+file1.getAbsolutePath()+"<br/>"); } finally{ ous.close(); ins.close(); }In this way, we complete the upload of the file.
fileUpload.html
<form action="servlet/UploadServlet" method="post" enctype="multipart/form-data"> <div align="center"> <fieldset> <legend>Upload file</legend><br/> <div align="left">Upload file1</div> <div align="left">Upload file1</div> <div align="left"> <input type="file" name="file1"/> </div> <div align="left">Upload file2</div> <div align="left"> <input type="file" name="file2"/> </div> <div> <div align='left'>Upload file instructions1</div> <div align='left'><input type="text" name="description1"/></div> </div> <div> <div align='left'>Upload file instructions2</div> <div align='left'><input type="text" name="description2"/></div> </div> <div> <div align='left'> <input type='submit' value="upload file"/> </div> </fieldset> </div> </form>
web.xml
<servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.test.hello.UploadServlet</servlet-class> </servlet><servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/servlet/UploadServlet</url-pattern> </servlet-mapping>
UploadServlet.java
package com.test.hello;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.DiskFileUpload;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;public class UploadServlet extends HttpServlet { /** * Constructor of the object. */ public UploadServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.getWriter().println("Please upload the file in POST"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ @SuppressWarnings({ "unchecked", "deprecation" }) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File file1 = null,file2=null; String description1 = null,description2 = null; response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); DiskFileUpload diskFileUpload = new DiskFileUpload(); try{ List<FileItem> list = diskFileUpload.parseRequest(request); out.println("Transfer all FileItems...<br/>"); for(FileItem fileItem : list){ if(fileItem.isFormField()){ if("description1".equals(fileItem.getFieldName())){ out.println("Transfer to description1 ... <br/>"); description1 = new String(fileItem.getString().getBytes(),"UTF-8"); } if("description2".equals(fileItem.getFieldName())){ out.println("Travel to description2 ... <br/>"); description2 = new String(fileItem.getString().getBytes(),"UTF-8"); } }else{ if("file1".equals(fileItem.getFieldName())){ File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8")); out.println("Travel to file1...<br/>"); out.println("Client file location: "+remoteFile.getAbsolutePath()+"<br/>"); file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName()); file1.getParentFile().mkdirs(); file1.createNewFile(); InputStream ins = fileItem.getInputStream(); OutputStream ous = new FileOutputStream(file1); try{ byte[] buffer = new byte[1024]; int len = 0; while((len = ins.read(buffer)) > -1) ous.write(buffer,0,len); out.println("to save the file"+file1.getAbsolutePath()+"<br/>"); } finally{ ous.close(); ins.close(); } } if("file2".equals(fileItem.getFieldName())){ File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8")); out.println("Travel to file2...<br/>"); out.println("Client file location: "+remoteFile.getAbsolutePath()+"<br/>"); file2 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName()); file2.getParentFile().mkdirs(); file2.createNewFile(); InputStream ins = fileItem.getInputStream(); OutputStream ous = new FileOutputStream(file2); try{ byte[] buffer = new byte[1024]; int len = 0; while((len = ins.read(buffer)) > -1) ous.write(buffer,0,len); out.println("to save file"+file2.getAbsolutePath()+"<br/>"); } finally{ ous.close(); ins.close(); } } } out.println("Request parsing is completed<br/><br/>"); } } catch(FileUploadException e){} out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); if(file1 != null){ out.println("<div>"); out.println(" <div align='left'>file1;</div>"); out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+ file1.getName()+"'target=_blank>"+file1.getName()+"</a>"); out.println("</div>"); out.println("</div>"); } if(file2 != null){ out.println("<div align='left'>file2;</div>"); out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+ file2.getName()+"'target=_blank>"+file2.getName()+"</a>"); out.println("</div>"); out.println("</div>"); } out.println("<div>"); out.println(" <div align='left'>description1:</div>"); out.println(" <div align='left'>"); out.println(description1); out.println("</div>"); out.println("</div>"); out.println("</div>"); out.println(" <div align='left'>description2:</div>"); out.println(" <div align='left'>description2:</div>"); out.println(" <div align='left'>"); out.println("</div>"); out.println("</div>"); out.println("</BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}Running example
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.