MultipartFile(文件的上传)

摘自:https://www.cnblogs.com/896240130Master/p/6430908.html

   https://blog.csdn.net/kouwoo/article/details/40507565

注意:单文件MultipartFile file

   多文件(定义为数组形式)MultipartFile[] file

判断文件是否为空:!file.isEmpty() -- 不为空

文件保存路径 :String filePath = request.getSession().getServletContext().getRealPath("/") 

               + "upload/" + file.getOriginalFilename();

上传文件原名:file.getOriginalFilename();

转存文件 :file.transferTo(new File(filePath));

步骤:1、创建一个控制类

   2、编写提交表单的action

   3、使用SpringMVC注解RequestParam来指定表单中的file参数;

   4、指定一个用于保存文件的web项目路径

   5、通过MultipartFile的transferTo(File dest)这个方法来转存文件到指定的路径。

  MultipartResolver其中属性详解:

    defaultEncoding="UTF-8" 是请求的编码格式,默认为iso-8859-1
    maxUploadSize="5400000" 是上传文件的大小,单位为字节
    uploadTempDir="fileUpload/temp" 为上传文件的临时路径

 1 <body>  
 2 <h2>文件上传实例</h2>  
 3   
 4   
 5 <form action="fileUpload.html" method="post" enctype="multipart/form-data">  
 6     选择文件:<input type="file" name="file">  
 7     <input type="submit" value="提交">   
 8 </form>  
 9   
10   
11 </body>  
View Code

注意要在form标签中加上enctype="multipart/form-data"表示该表单是要处理文件的,input的type属性的属性值设为file,

标签中属性type的值为file,且name属性的值为myFile,之所以需要name属性值,是因为在使用接口MultipartHttpServletRequest的getFile方法时需要使用name属性的值。例如在清单7-33中,代码中的upload操作会从请求中读取上传文件。

读取上传文件

def upload = {

def file = request.getFile('myFile')

// 处理该文件

}

注意getFile方法不会返回一个java.io.File的实例,而是返回org.springframework.web. multipart.MultipartFile的一个实例,关于org.springframework.web.multipart.MultipartFile的详细信息,请参考清单7-34。如果在请求中没有找到文件则getFile方法返回null。

清单7-34 org.springframework.web.multipart.MultipartFile接口

 1 interface MultipartFile {
 2 
 3 public byte[] getBytes();
 4 
 5 public String getContentType();
 6 
 7 public java.io.InputStream getInputStream();
 8 
 9 public String getName();
10 
11 public String getOriginalFilename();
12 
13 public long getSize();
14 
15 public boolean isEmpty();
16 
17 public void transferTo(java.io.File dest);
18 
19 }
View Code
 1     @RequestMapping("fileUpload")  
 2     public String fileUpload(@RequestParam("file") MultipartFile file) {  
 3         // 判断文件是否为空  
 4         if (!file.isEmpty()) {  
 5             try {  
 6                 // 文件保存路径  
 7                 String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"  
 8                         + file.getOriginalFilename();  
 9                 // 转存文件  
10                 file.transferTo(new File(filePath));  
11             } catch (Exception e) {  
12                 e.printStackTrace();  
13             }  
14         }  
15         // 重定向  
16         return "redirect:/list.html";  
17     }  
View Code

         

自古英雄出炼狱,从来富贵入凡尘。
原文地址:https://www.cnblogs.com/yunliu0603/p/9504756.html