Q: what are the ways to upload files in JavaWeb?

Last time we talked about how files can be downloaded, this time we’ll talk briefly about how files can be uploaded in different environments. File upload mode

Servlet2.5 Servlet3.0 SpringMVCCopy the code

The case uses Servlet2.5

File upload involves the preparation of the front page and background server-side code preparation, the front to send the file, the background to receive and save the file, this is a complete file upload.

  1. The front desk page

When uploading files, there will be an interface for uploading files. First, we need a form, and the form request mode is POST. Second, the encType of our form must be set to “multipart/form-data”, that is, encType = “multipart/form-data”, which means setting the MIME encoding of the form. By default this encoding format is “Application/X-www-form-urlencoded” and cannot be used for file uploads; File data can only be passed in its entirety if multipart/form-data is used.


12 3 4 5 6 7 8 9 10 11 12 13Copy the code
  1. Background Commons-fileupload usage

Commons.apache.org/ download commons-io and Commons-fileupload jar resources. Unzip and import into the project. Commons -fileupload.jar is a core fileupload package. Commons – IO. Jar is a dependency package of fileupload and a toolkit.

Introduce some of the core classes used

DiskFileItemFactory – Sets the disk space and holds temporary files. It’s just a utility class

ServletFileUpload – A core class for file uploading that receives and parses requests

ServletFileUpload. ParseRequest (request); – List Parses the request

1, Create a DiskFileItemFactory factory class and specify the temporary file and size

Create a ServletFileUpload core class to receive temporary files and convert the requested files

3. The ServletFileUpload class transforms the original request to get the FileItem collection

4. Iterate through each element in the collection and process

5. Determine if each element is a normal form item, and if so, treat it as a normal form item

6. If it is not a normal form item, it is a file, which is processed by processing (upload).

public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/ / set the encoding, can obtain Chinese file name request. SetCharacterEncoding (" utf-8 "); String path = getServletContext().getrealPath ("/upload"); // Temporary file directory String tempPath = getServletContext().getrealPath ("/temp"); / / check whether we have file upload request / / a Boolean isMultipart = ServletFileUpload. IsMultipartContent (the req); DiskFileItemFactory = DiskFileItemFactory; DiskFileItemFactory Disk = new DiskFileItemFactory(1024 * 10, new File(tempPath)); // 2, declare ServletFileUpload, accept the above temporary file. The default value ServletFileUpload up = new ServletFileUpload(disk); ParseRequest (request) {List<FileItem> List = up.parserequest (request); if (list.size() > 0) { for (FileItem file : List) {if (file.isformField ()) {String fieldName = file.getFieldName(); String value = file.getString(); // String value = file.getString(); String value = file.getString("UTF-8"); System.out.println(fieldName + "=" + value); String fileName = file.getName();} else {String fileName = file.getName(); System.out.println(file.getFieldName()); // process fileName fileName = filename.substring (filename.lastindexof ("\\") + 1); System.out.println("old Name : " + fileName); String extName = filename.subString (filename.lastIndexof (".")); String newName = UUID.randomUUID().toString().replace("-", "") + extName; File.write (new file (path + "/" + newName)); System.out.println(" fileName is: "+ fileName); System.out.println(" File size is: "+ file.getsize ()); file.delete(); } } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }}Copy the code

}

12 34 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54Copy the code

Servlet3.0 way

Use the annotation @multipartConfig to identify a Servlet as supporting file uploads. Servlet3.0 encapsulates multipart/form-data POST requests into parts, and uses parts to perform operations on uploaded files.

The front desk



12 3 4 5 6 7 8 9 10 11 12 13 14Copy the code

The background

@WebServlet(“/upload”) @MultipartConfig public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {system.out.println (" Upload file... ); / / set the coding request. SetCharacterEncoding (" utf-8 "); // Get the plain form item parameter String uname = request.getParameter("uname"); System.out.println(uname); Request.getpart (name) : Name represents the name attribute value of the file element in the form. Part Part = Request.getPart ("myfile"); / / get the path of the file storing the String path = request. GetServletContext () getRealPath ("/"); / / get the file name String fileName = part. GetSubmittedFileName (); // Upload part.write(path + fileName); }Copy the code

}

12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24Copy the code

For SpringMVC way

Pom file modification adds commons-Fileupload dependencies

< the groupId > Commons fileupload - < / groupId > < artifactId > Commons fileupload - < / artifactId > < version > 1.3.2 < / version >Copy the code
1, 2, 3, 4, 5, 6, 7, 8, 9Copy the code

servlet-context.xml

<property name="maxUploadSize"> 

<value>104857600</value> 

</property> 

<property name="maxInMemorySize"> 

<value>4096</value> 

</property> 
Copy the code
12 3 4 5 6 7 8 9 10 11 12 13 14 15Copy the code

FileController

import java.io.File;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.multipart.MultipartHttpServletRequest;

import org.springframework.web.servlet.ModelAndView;

@Controller

public class FileController {

@RequestMapping("/uploadFile") public ModelAndView uploadFile(HttpServletRequest request){ ModelAndView mv=new ModelAndView(); mv.setViewName("result"); MultipartHttpServletRequest mr=(MultipartHttpServletRequest) request; MultipartFile multipartFile= mr.getFile("file"); String path=request.getSession().getServletContext().getRealPath("upload"); System.out.println(path); if(null! =multipartFile&&! multipartFile.isEmpty()){ String fileName=multipartFile.getOriginalFilename(); try { multipartFile.transferTo(new File(path,fileName)); Mv. addObject(" MSG ", "file uploaded successfully!") ); } catch (Exception e) {mv.addobject (" MSG ", "upload failed!") ); e.printStackTrace(); } } return mv; }Copy the code

}

12 34 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 59 60 61Copy the code

The form at the front desk

<input type="file" name="file"/> <button type="submit">Copy the code
One, two, three, four, five, six, sevenCopy the code

Extension to MIME

Multipurpose Internet Mail Extensions (MIME) Multipurpose Internet Mail Extensions. A type of file with a specified extension that the browser automatically opens when the file is accessed using the specified application. It is used to specify the name of a file customized by the client and the opening mode of some media files.

It is an Internet standard that extends the E-mail standard to support:

Non-ascii character text; Non-text attachments (binary, sound, image, etc.); A message body consisting of multiple parts; Header information containing non-ASCII characters.

This standard is defined in RFC 2045, RFC 2046, RFC 2047, RFC 2048, RFC 2049, etc. MIME improves on RFC 2822, a conversion from RFC 822, which stated that the E-mail standard did not allow the use of characters outside the 7-bit ASCII character set in mail messages. Because of this, some non-English character messages and non-text messages such as binaries, images, and sounds cannot be transmitted in E-mail (MIME can). MIME specifies symbolic methods for representing a wide variety of data types. In addition, the MIME framework is used in the HTTP protocol used in the World Wide Web, and the standard is extended to include Internet media types.

Use Tomcat as an example. You can view all the MIME types in the web. XML file. Press Ctrl + F to search for the MIME types you want to know.

. MIME improves on RFC 2822, a conversion from RFC 822, which stated that the E-mail standard did not allow the use of characters outside the 7-bit ASCII character set in mail messages. Because of this, some non-English character messages and non-text messages such as binaries, images, and sounds cannot be transmitted in E-mail (MIME can). MIME specifies symbolic methods for representing a wide variety of data types. In addition, the MIME framework is used in the HTTP protocol used in the World Wide Web, and the standard is extended to include Internet media types.

Use Tomcat as an example. You can view all the MIME types in the web. XML file. Press Ctrl + F to search for the MIME types you want to know.