What are the ways to implement file upload in JavaWeb?

What are the ways to implement file upload in JavaWeb?

Last time we talked about the ways of downloading files. This time we will briefly talk about the ways of uploading files from different environments.

File upload method

  • Servlet2.5 way
  • Servlet3.0 way
  • SpringMVC way

Case practice

Servlet2.5 way

File upload involves the writing of front-end pages and the writing of back-end server-side code. The front-end sends files, and the back-end receives and saves files. This is a complete file upload.

1) Front page

When uploading files, there will be an interface for uploading files. 1. we need a form, and the request method of the form is POST ; secondly, the enctype of our form must be set to "multipart/form-data", that is, enctype=" "multipart/form-data" means to set the MIME encoding of the form. By default, this encoding format is "application/x-www-form-urlencoded" and cannot be used for file upload; only when multipart/form-data is used can the file data be completely transmitted.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> </title>
</head>
<body>
	<form action="uploadServlet" method="post" enctype="multipart/form-data">
		 <input type="file" name="myfile"/>
		<input type="submit" value=" "/>
	</form>
</body>
</html>
 

2) Use of background commons-fileupload

1. you need to import the third-party jar package, commons.apache.org/download commons-io and commons-fileupload two jar resources. Unzip and import into the project. commons-fileupload.jar is the core package for file upload. commons-io.jar is a dependency package of fileupload and a toolkit at the same time.

Introduce several core classes used

DiskFileItemFactory -Set the disk space and save temporary files. Just a tool

ServletFileUpload -the core class for file upload, this class receives requests and parses them

ServletFileUpload.parseRequest(request) ; List parse request

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

2. Create the ServletFileUpload core class, receive temporary files, and do the requested conversion

3. Convert the original request through the ServletFileUpload class to get the FileItem collection

4. Traverse and process each element in the collection

5. Determine whether each element is a normal form item, and if it is, it will be processed as a normal form item

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

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

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 
		request.setCharacterEncoding("UTF-8");
		// tomcat upload 
		String path = getServletContext().getRealPath("/upload");
		// 
		String tempPath = getServletContext().getRealPath("/temp");
		// 
		//boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		//1 DiskFileItemFactory 
		DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, new File(tempPath));
		//2 ServletFileUpload 
		ServletFileUpload up = new ServletFileUpload(disk);
		//3 request
		try {
			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("UTF-8");
						System.out.println(fieldName + "=" + value);
					} else { // 
						// 
						String fileName = file.getName();
						System.out.println(file.getFieldName());
						// 
						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);
						System.out.println(" " + file.getSize());
						file.delete();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
 

Servlet3.0 way

Use the annotation @MultipartConfig to identify a servlet as supporting file upload. Servlet3.0 encapsulates the POST request of multipart/form-data into Part, and operates the uploaded file through Part.

Front desk

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> </title>
</head>
<body>
	<form action="upload" method="post" enctype="multipart/form-data">
		 <input type="text" name="uname"/>
		 <input type="file" name="myfile"/>
		<input type="submit" value=" "/>
	</form>
</body>
</html>
 

Backstage

@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(" ...");
		// 
		request.setCharacterEncoding("UTF-8");
		// 
		String uname = request.getParameter("uname");
		System.out.println(uname);
		// 
		// part  request.getpart(name) name file name 
		Part part = request.getPart("myfile");
		// 
		String path = request.getServletContext().getRealPath("/");
		// 
		String fileName = part.getSubmittedFileName();
		// 
		part.write(path + fileName);
	}

}
 

SpringMVC way

Pom file modification adds commons-fileupload dependency

<dependency> 

    <groupId>commons-fileupload</groupId> 

    <artifactId>commons-fileupload</artifactId> 

    <version>1.3.2</version> 

</dependency> 
 

servlet-context.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <property name="maxUploadSize"> 

    <value>104857600</value> 

    </property> 

    <property name="maxInMemorySize"> 

    <value>4096</value> 

    </property> 

</bean> 
 

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", " !"); 

        } catch (Exception e) { 

        	mv.addObject("msg", " !"); 

        	e.printStackTrace(); 

        } 

        } 

        return mv; 

	} 

} 
 

Front-end form

<form action="uploadFile" method="post" enctype="multipart/form-data"> 

	<input type="file" name="file"/> 

	<button type="submit">  </button> 

</form> 
 

Extension ~MIME

MIME (Multipurpose Internet Mail Extensions) multipurpose Internet mail extension type. It is a way to set a file with a certain extension to be opened by an application. When the file with the extension is accessed, the browser will automatically use the specified application to open it. It is mostly used to specify some client-defined file names, as well as some media file opening methods.

It is an Internet standard that extends the e-mail standard to enable it to support:

Non-ASCII character text; non-text format attachments (binary, sound, image, etc.); message body composed of multiple parts; header information containing non-ASCII characters.

This standard is defined in RFC 2045, RFC 2046, RFC 2047, RFC 2048, RFC 2049 and other RFCs . MIME improves RFC 2822, which is transformed from RFC 822. These old standards stipulate that email standards do not allow characters outside the 7-bit ASCII character set to be used in email messages. Because of this, some non-English character messages and binary files, images, sounds and other non-text messages cannot be transmitted in e-mail originally (MIME can). MIME specifies the symbolization method used to represent various data types. In addition, the MIME framework is also used in the HTTP protocol used in the World Wide Web, and the standard is extended to Internet media types.

To view the MIME types corresponding to different files, I recommend a way. Take Tomcat as an example. The web.xml file below it can view all the MIME types. You can quickly find the MIME type of the file you want to know by searching with Ctrl + F.