springMVC upload image

1. You need to import the jar package uploaded by the springmvc file, otherwise there will be an exception java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory

2. Create an upload page form

1 <form action="upload/uploadPic.do" method="post" enctype="multipart/form-data">
2         <input type="file" name="pic">
3         <br>
4         <input type="submit" value="submit">
5     </form>

Third, set the file upload configuration in the springMVC configuration file

1 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
2         <!-- 以字节为单位  -->
3         <property name="maxUploadSize" value="1024000"></property>
4     </bean>

Fourth, the preparation of the controller class

1  // Jump to form page 
2      @RequestMapping("/toForm.do" )
 3      public String toForm(){
 4          return "form1" ;
 5      }
 6      
7      // File upload 
8      @RequestMapping("/uploadPic.do" )
 9      public String uploadPic(HttpServletRequest req) throws IOException{
 10          MultipartHttpServletRequest mr = (MultipartHttpServletRequest) req;
 11          // Get file 
12          MultipartFile file = mr.getFile("pic" );
 13          //Get file byte array 
14          byte [] bs = file.getBytes();
 15          // Create file name according to time and random number 
16          String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format( new Date());
 17          Random random = new Random();
 18          for ( int i = 0;i < 3;i++ ){
 19              fileName = fileName + random.nextInt(10 );
 20          }
 21          // Get the original filename of the file 
22          String originalFilename = file .getOriginalFilename();
 23          //Cut the original file name to get the suffix 
24          String suffix = originalFilename.substring(originalFilename.lastIndexOf("." ));
 25          // Get the project path 
26          String realPath = req.getSession().getServletContext().getRealPath("/ " );
 27          // Create byte output stream 
28          OutputStream out = new FileOutputStream( new File(realPath + "/upload/" + fileName + suffix));
 29          out.write(bs);
 30          out.flush();
 31          out.close();
 32          return "success" ;
 33      }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324752832&siteId=291194637