Use the Spring framework to upload files

Source: Internet
Author: User

Use the Spring framework to upload files
There are multiple ways to upload files in Java, such as smartUpload or Strus2. This article will share with you how to use the MultipartFile class in the Spring framework to upload instance files.

Don't worry, just pick up the goods directly. First, a file upload class FileUploadingUtil is compiled. This class defines two open methods, upload and getFileMap.

The former needs to pass in a Map parameter, which is a list of files in the form submitted by the user. The final returned value is also a Map object whose key name is the name of the uploaded file, the key value is the storage path of the file on the server. The latter is mainly used for testing purposes and is not a major function. You can ignore this method.

 

Package com. emerson. cwms. utils; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import java. util. date; import java. util. hashMap; import java. util. iterator; import java. util. map; import java. util. map. entry; import org. springframework. web. multipart. multipartFile;/*** file upload tool class ** @ author Chris Mao (Zibing) **/public class FileUploadingUtil {/*** save path on the server, assign a value to the Controller using the upload function */public static String FILEDIR = null;/*** to upload multiple files, return the file name and server storage path list ** @ param files * @ return * @ throws IOException */public static Map
 
  
Upload (Map
  
   
Files) throws IOException {File file = new File (FILEDIR); if (! File. exists () {file. mkdir ();} Map
   
    
Result = new HashMap
    
     
(); Iterator
     
      
> Iter = files. entrySet (). iterator (); while (iter. hasNext () {MultipartFile aFile = iter. next (). getValue (); if (aFile. getSize ()! = 0 &&! "". Equals (aFile. getName () {result. put (aFile. getOriginalFilename (), uploadFile (aFile) ;}} return result;}/*** upload a single file, and return the storage path ** @ param aFile * @ return * @ throws FileNotFoundException * @ throws IOException */private static String uploadFile (MultipartFile aFile) in the server) throws IOException {String filePath = initFilePath (aFile. getOriginalFilename (); try {write (aFile. getInputStream (), new FileOutputSt Ream (filePath);} catch (FileNotFoundException e) {logger. error ("uploaded file:" + aFile. getName () + "does not exist !! "); E. printStackTrace ();} return filePath;}/*** write data ** @ param in * @ param out * @ throws IOException */private static void write (InputStream in, outputStream out) throws IOException {try {byte [] buffer = new byte [1024]; int bytesRead =-1; while (bytesRead = in. read (buffer ))! =-1) {out. write (buffer, 0, bytesRead);} out. flush ();} finally {try {in. close (); out. close ();} catch (IOException ex) {}}/*** traverses the Server Directory and lists all files (including subdirectories) in the directory * @ return */public static Map
      
        GetFileMap () {logger.info (FileUploadingUtil. FILEDIR); Map
       
         Map = new HashMap
        
          (); File [] files = new File (FileUploadingUtil. FILEDIR). listFiles (); if (files! = Null) {for (File file: files) {if (file. isDirectory () {File [] files2 = file. listFiles (); if (files2! = Null) {for (File file2: files2) {String name = file2.getName (); logger.info (file2.getParentFile (). getAbsolutePath (); logger.info (file2.getAbsolutePath (); map. put (file2.getParentFile (). getName () + "/" + name, name. substring (name. lastIndexOf ("_") + 1); }}}} return map;}/*** returns the file storage path. To prevent duplicate files from being overwritten, added the random number * @ param name * @ return */private static String initFilePath (String name) {String dir = getFi to the file name. LeDir (name) + ""; File file = new File (FILEDIR + dir); if (! File. exists () {file. mkdir ();} Long num = new Date (). getTime (); Double d = Math. random () * num; return (file. getPath () + "/" + num + d. longValue () + "_" + name ). replaceAll ("", "-");}/***** @ param name * @ return */private static int getFileDir (String name) {return name. hashCode () & 0xf ;}}
        
       
      
     
    
   
  
 

Controller code. Use the FileUploadingUtil class defined above to upload files.

 

 

Package com. emerson. cwms. web; import java. io. IOException; import java. util. iterator; import java. util. map; import java. util. map. entry; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. springframework. stereotype. controller; import org. springframework. ui. model; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. bind. annotation. requestMethod; import org. springframework. web. multipart. multipartHttpServletRequest; import com. emerson. cwms. utils. fileUploadingUtil;/*** File Upload Controller ** @ author Chris Mao (Zibing) **/@ Controller @ RequestMapping (value = "/files ") public class FileController {@ RequestMapping (value = "/", method = RequestMethod. GET) public String list (HttpServletRequest request, HttpServletResponse response, Model model) {iniFileDir (request); System. out. println (request. getAttribute ("files"); model. addAttribute ("files", FileUploadingUtil. getFileMap (); return "files/list" ;}@ RequestMapping (value = "/upload", method = RequestMethod. POST) public String doUpload (HttpServletRequest request) {iniFileDir (request); try {MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; Map
 
  
UploadedFiles = FileUploadingUtil. upload (mRequest. getFileMap (); Iterator
  
   
> Iter = uploadedFiles. entrySet (). iterator (); while (iter. hasNext () {Entry
   
    
Each = iter. next (); System. out. print ("Uploaded File Name =" + each. getKey (); System. out. println (", Saved Path in Server =" + each. getValue () ;}} catch (Exception e) {e. printStackTrace ();} return "redirect:/files/";} private void iniFileDir (HttpServletRequest request) {FileUploadingUtil. FILEDIR = request. getSession (). getServletContext (). getRealPath ("/") + "files/"; if (FileUploadingUtil. FILEDIR = null) {FileUploadingUtil. FILEDIR = request. getSession (). getServletContext (). getRealPath ("/") + "files /";}}}
   
  
 

Note: you must add reference to commons-fileupload In the pom. xml file. Otherwise, the code will prompt that the FileItemFactory class error cannot be found during running.

 

The reference is as follows.

 

 
  
   commons-fileupload
  commons-fileupload
  
   1.3.1
  
 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.