Web file uploading uses POST. Unlike POST submitting forms, uploading files requires setting the enctype attribute of FORM to multipart/form-data. Since the uploaded files will be relatively large, this parameter needs to be set to specify that the browser uses binary upload. If not set, the enctype property defaults to application/x-www-form-urlencoded. Using the browser will use ASCII to send data to the server, resulting in the failure to send the file.
To upload a file, use the file domain (<input type='file'/> and set the FORM's Enctype to multipart/form-data.
The client upload page is shown in the figure:
The code is as follows:
upload.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>Upload file</title><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="this is my page"><meta http-equiv="content-type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="css/style.css"></head><body><form action="servlet/UploadServlet" method="post" enctype="multipart/form-data"><div align="center"><br/> <fieldset> <legend>Upload file</legend><br/> <div class='line'> <div align='left'>Upload file 1</div> <div align='left'> <input type="file" name="file1"> </div> </div> <div class='line'> <div align='left'>Upload file 2</div> <div align='left'>Upload file 2</div> <div align='left'> align='left'> <input type="file" name="file2"> </div> </div> <div class='line'> <div align='left'>Upload file description 1</div> <div align='left'><input type="text" name="description1"></div> </div> <div class='line'> <div align='left'>Upload file description 2</div> <div align='left'><input type="text" name="description2"></div> </div> <div class='line'> <div align='left'>Upload file description 2</div> <div align='left'></div> <div align='left'><br/> <input type="submit" value=" Upload file"> </div> </div> </fieldset></div></form></body></html>
The code run by the client is very simple, and the server is more complicated. To obtain the contents, the request submitted by the browser must be parsed according to the format specified by the HTTP protocol.
It is more troublesome to parse binary streams. Many class libraries have already completed this work. For example, SmartUpload and Apache Commons Fileupload.SmartUpload is a commercial class library. The data is stored in memory during the parsing of the Request process, so it is faster, but memory overflow occurs when uploading larger files. Apache Commons Fileupload is a free and open source class library. Some frameworks such as Struts integrate the Apache Common Fileupload class library to implement file uploads.
As shown in the figure:
The code is as follows:
package com.helloweenvsfei.servlet;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.net.URLEncoder;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 { private static final long serialVersionUID = 7523024737218332088L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.getWriter().println("Please upload the file in POST"); } @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File file1 = null, file2 = null; String description1 = null, description2 = null; response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <link rel='stylesheet' type='text/css' href='../css/style.css'>"); out.println(" <BODY>"); out.println("<div align=center><br/>"); out.println("<fieldset style='width:90%'><legend>Upload file</legend><br/>"); out.println(" <div class='line'>"); out.println(" <div align='left' class='leftDiv'>Upload log: </div>"); out.println(" <div align='left' class='rightDiv'>"); // Use DiskFileUpload object to parse request DiskFileUpload diskFileUpload = new DiskFileUpload(); try { // Place the parsed result in List List<FileItem> list = diskFileUpload.parseRequest(request); out.println("Trace through all FileItems ... <br/>"); //Trace through list All FileItems in the FileItem fileItem : list){ if(fileItem.isFormField()){ // If it is a text field if("description1".equals(fileItem.getFieldName())){ // If the FileItem name is description1 out.println("Travel to description1 ... <br/>"); description1 = new String(fileItem.getString().getBytes(), "UTF-8"); } if("description2".equals(fileItem.getFieldName())){ // If the FileItem is Name is description2 out.println("Travel to description2 ... <br/>"); description2 = new String(fileItem.getString().getBytes(), "UTF-8"); } } else{ // Otherwise, for the file field if("file1".equals(fileItem.getFieldName())){ // File object built by the client file path 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/>"); // Server-side file, place in the upload folder file1 = new File(this.getServletContext().getRealPath("attachment"), remoteFile.getName()); file1.getParentFile().mkdirs(); file1.createNewFile(); // Write a file and write the file content of FileItem into the file 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("Save file" + file1.getAbsolutePath() + "<br/>"); } finally{ ous.close(); ins.close(); } } if("file2".equals(fileItem.getFieldName())){ // File object built by client file path 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/>"); // Server-side file, put in the upload folder file2 = new File(this.getServletContext().getRealPath("attachment"), remoteFile.getName()); file2.getParentFile().mkdirs(); file2.createNewFile(); // Write a file and write the file contents of FileItem to the file 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("Save file" + file2.getAbsolutePath() + "<br/>"); } finally{ ous.close(); ins.close(); } } } } out.println("Request parsing is completed"); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.println(" </div>"); out.println(" <div align='left' class='leftDiv'>file1:</div>"); out.println(" <div align='left' class='rightDiv'>"); out.println(" <a href='" + request.getContextPath() + "/attachment/" + file1.getName() + "' target=_blank>" + file1.getName() + "</a>" ); out.println(" </div>"); out.println(" </div>"); } if(file2 != null){ out.println(" <div class='line'>"); out.println(" <div align='left' class='leftDiv'>file2:</div>"); out.println(" <div align='left' class='rightDiv'>"); out.println(" <a href='" + request.getContextPath() + "/attachment/" + URLEncoder.encode(file2.getName(), "UTF-8") + "' target=_blank>" + file2.getName() + "</a>" ); out.println(" </div>"); out.println(" </div>"); } out.println(" <div class='line'>"); out.println(" <div align='left' class='leftDiv'>description1:</div>"); out.println(" <div align='left' class='rightDiv'>"); out.println(" <div align='left' class='rightDiv'>"); out.println(" <div align='left' class='leftDiv'>description2:</div>"); out.println(" <div align='left' class='rightDiv'>"); out.println(description2); out.println(" </div>"); out.println(" </div>"); out.println(" </fieldset></div>"); out.println(" </BODY>"); out.println(" </HTML>"); out.flush(); out.close(); }}The program operation effect is shown in the figure:
This article has been compiled into "Summary of Java Upload Operation Techniques", and everyone is welcome to learn and read.
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.