Spring mvc-File Upload
When uploading a file, we need to use the file upload parser. In fact, it is no stranger. It is just an extension of httpServletRequest, so that it can better process file uploads. The extension interface name is: org. springframework. web. multipart. multipartHttpServletRequest
First, let's take a look at the underlying architecture of the class diagram:
The following code shows how to implement it:
1. Configure in web. xml
Org. springframework. web. multipart. commons. CommonsMultipartResolver>
2. Implement file upload in Controller
@ Controller @ RequestMapping (/file) public class UploadController {@ RequestMapping (value =/upload) public String addUser (@ RequestParam (File) CommonsMultipartFile file, HttpServletRequest request) throws IOException {System. out. println (fileName ---> + file. getOriginalFilename (); if (! File. isEmpty () {try {// defines the file path FileOutputStream OS = new FileOutputStream (D: // + new Date (). getTime () + file. getOriginalFilename (); // upload the file InputStream in = file. getInputStream (); int B = 0; // if the file content is empty while (B = in. read ())! =-1) {OS. write (B);} OS. flush (); // refresh the OS. close (); in. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}return/success ;}
3. Create a page in jsp
Note: The two highlighted fonts must be consistent.