SpringMVC的文件上传

使用Spring框架实现文件上传

在Java中实现文件的上传有多种方式,如smartUpload或是使用Strus2,本文与大家分享使用Spring框架中的MultipartFile类来实例文件的上传。

不啰嗦了,直接上干货。先是编写了一个实现文件上传的类FileUploadingUtil,此类中定义了两个对外公开的方法,upload和getFileMap。

前者需要传入一个Map参数,是用户提交的表单中的文件列表,最终返回值的也是一个Map类型对象,其键名为上传的文件名称,键值为文件在服务器上的存储路径;后者主要是用于测试用途,非主要功能,看官可以忽略此方法。

 

Java代码   收藏代码
  1. package com.emerson.cwms.utils;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10. import java.util.Date;  
  11. import java.util.HashMap;  
  12. import java.util.Iterator;  
  13. import java.util.Map;  
  14. import java.util.Map.Entry;  
  15.   
  16. import org.springframework.web.multipart.MultipartFile;  
  17.   
  18. /** 
  19.  * 文件上传工具类 
  20.  *  
  21.  * @author Chris Mao(Zibing) 
  22.  * 
  23.  */  
  24. public class FileUploadingUtil {  
  25.   
  26.     /** 
  27.      * 服务器上的保存路径,在使用到上传功能的Controller中对其进行赋值 
  28.      */  
  29.     public static String FILEDIR = null;  
  30.   
  31.     /** 
  32.      * 上传多个文件,返回文件名称和服务器存储路径列表 
  33.      *  
  34.      * @param files 
  35.      * @return 
  36.      * @throws IOException 
  37.      */  
  38.     public static Map<String, String> upload(Map<String, MultipartFile> files) throws IOException {  
  39.         File file = new File(FILEDIR);  
  40.         if (!file.exists()) {  
  41.             file.mkdir();  
  42.         }  
  43.   
  44.         Map<String, String> result = new HashMap<String, String>();  
  45.         Iterator<Entry<String, MultipartFile>> iter = files.entrySet().iterator();  
  46.         while (iter.hasNext()) {  
  47.             MultipartFile aFile = iter.next().getValue();  
  48.             if (aFile.getSize() != 0 && !"".equals(aFile.getName())) {  
  49.                 result.put(aFile.getOriginalFilename(), uploadFile(aFile));  
  50.             }  
  51.         }  
  52.         return result;  
  53.     }  
  54.   
  55.     /** 
  56.      * 上传单个文件,并返回其在服务器中的存储路径 
  57.      *  
  58.      * @param aFile 
  59.      * @return 
  60.      * @throws FileNotFoundException 
  61.      * @throws IOException 
  62.      */  
  63.     private static String uploadFile(MultipartFile aFile) throws IOException {  
  64.         String filePath = initFilePath(aFile.getOriginalFilename());  
  65.         try {  
  66.             write(aFile.getInputStream(), new FileOutputStream(filePath));  
  67.         } catch (FileNotFoundException e) {  
  68.             logger.error("上传的文件: " + aFile.getName() + " 不存在!!");  
  69.             e.printStackTrace();  
  70.         }  
  71.         return filePath;  
  72.     }  
  73.   
  74.     /** 
  75.      * 写入数据 
  76.      *  
  77.      * @param in 
  78.      * @param out 
  79.      * @throws IOException 
  80.      */  
  81.     private static void write(InputStream in, OutputStream out) throws IOException {  
  82.         try {  
  83.             byte[] buffer = new byte[1024];  
  84.             int bytesRead = -1;  
  85.             while ((bytesRead = in.read(buffer)) != -1) {  
  86.                 out.write(buffer, 0, bytesRead);  
  87.             }  
  88.             out.flush();  
  89.         } finally {  
  90.             try {  
  91.                 in.close();  
  92.                 out.close();  
  93.             } catch (IOException ex) {  
  94.             }  
  95.         }  
  96.     }  
  97.   
  98.     /** 
  99.      * 遍历服务器目录,列举出目录中的所有文件(含子目录) 
  100.      * @return 
  101.      */  
  102.     public static Map<String, String> getFileMap() {  
  103.         logger.info(FileUploadingUtil.FILEDIR);  
  104.         Map<String, String> map = new HashMap<String, String>();  
  105.         File[] files = new File(FileUploadingUtil.FILEDIR).listFiles();  
  106.         if (files != null) {  
  107.             for (File file : files) {  
  108.                 if (file.isDirectory()) {  
  109.                     File[] files2 = file.listFiles();  
  110.                     if (files2 != null) {  
  111.                         for (File file2 : files2) {  
  112.                             String name = file2.getName();  
  113.                             logger.info(file2.getParentFile().getAbsolutePath());  
  114.                             logger.info(file2.getAbsolutePath());  
  115.                             map.put(file2.getParentFile().getName() + "/" + name,  
  116.                                     name.substring(name.lastIndexOf("_") + 1));  
  117.                         }  
  118.                     }  
  119.                 }  
  120.             }  
  121.         }  
  122.         return map;  
  123.     }  
  124.   
  125.     /** 
  126.      * 返回文件存储路径,为防止重名文件被覆盖,在文件名称中增加了随机数 
  127.      * @param name 
  128.      * @return 
  129.      */  
  130.     private static String initFilePath(String name) {  
  131.         String dir = getFileDir(name) + "";  
  132.         File file = new File(FILEDIR + dir);  
  133.         if (!file.exists()) {  
  134.             file.mkdir();  
  135.         }  
  136.         Long num = new Date().getTime();  
  137.         Double d = Math.random() * num;  
  138.         return (file.getPath() + "/" + num + d.longValue() + "_" + name).replaceAll(" ""-");  
  139.     }  
  140.   
  141.     /** 
  142.      *  
  143.      * @param name 
  144.      * @return 
  145.      */  
  146.     private static int getFileDir(String name) {  
  147.         return name.hashCode() & 0xf;  
  148.     }  
  149. }  


Controller代码,使用上述定义的FileUploadingUtil类实现文件上传之功能。

 

 

Java代码   收藏代码
  1. package com.emerson.cwms.web;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Iterator;  
  5. import java.util.Map;  
  6. import java.util.Map.Entry;  
  7.   
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.springframework.stereotype.Controller;  
  12. import org.springframework.ui.Model;  
  13. import org.springframework.web.bind.annotation.RequestMapping;  
  14. import org.springframework.web.bind.annotation.RequestMethod;  
  15. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  16.   
  17. import com.emerson.cwms.utils.FileUploadingUtil;  
  18.   
  19. /** 
  20.  * 文件上传控制器 
  21.  *  
  22.  * @author Chris Mao(Zibing) 
  23.  * 
  24.  */  
  25. @Controller  
  26. @RequestMapping(value = "/files")  
  27. public class FileController {  
  28.       
  29.     @RequestMapping(value = "/", method = RequestMethod.GET)  
  30.     public String list(HttpServletRequest request, HttpServletResponse response, Model model) {  
  31.         iniFileDir(request);  
  32.           
  33.         System.out.println(request.getAttribute("files"));  
  34.         model.addAttribute("files", FileUploadingUtil.getFileMap());  
  35.         return "files/list";  
  36.     }  
  37.       
  38.     @RequestMapping(value = "/upload", method = RequestMethod.POST)  
  39.     public String doUpload(HttpServletRequest request) {  
  40.         iniFileDir(request);  
  41.           
  42.         try {  
  43.             MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;  
  44.             Map<String, String> uploadedFiles = FileUploadingUtil.upload(mRequest.getFileMap());  
  45.   
  46.             Iterator<Entry<String, String>> iter = uploadedFiles.entrySet().iterator();  
  47.             while (iter.hasNext()) {  
  48.                 Entry<String, String> each = iter.next();  
  49.                 System.out.print("Uploaded File Name = " + each.getKey());  
  50.                 System.out.println(", Saved Path in Server = " + each.getValue());  
  51.             }  
  52.         } catch (Exception e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.         return "redirect:/files/";  
  56.     }  
  57.   
  58.     private void iniFileDir(HttpServletRequest request) {  
  59.         FileUploadingUtil.FILEDIR = request.getSession().getServletContext().getRealPath("/") + "files/";  
  60.         if (FileUploadingUtil.FILEDIR == null) {  
  61.             FileUploadingUtil.FILEDIR = request.getSession().getServletContext().getRealPath("/") + "files/";  
  62.         }  
  63.     }  
  64. }  


注意事项:一定要在pom.xml文件中添加对commons-fileupload的依赖引用,否则代码在运行时会提示找不到FileItemFactory类的错误。

 

依赖引用如下。

 

Html代码   收藏代码
  1. <dependency>  
  2.     <groupId>commons-fileupload</groupId>  
  3.     <artifactId>commons-fileupload</artifactId>  
  4.     <version>1.3.1</version>  
  5. </dependency>  

 

猜你喜欢

转载自1960370817.iteye.com/blog/2289491