1. 程式人生 > >springMVC實現 MultipartFile 多文件上傳

springMVC實現 MultipartFile 多文件上傳

cat rect .com tor try class isempty param public

1、Maven引入所需的 jar 包(或自行下載)

     <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</
groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>

2、配置 spring 文件

  <!-- 多部分文件上傳 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
> <property name="defaultEncoding" value="utf-8"></property> <property name="maxUploadSize" value="10485760000"></property> <property name="maxInMemorySize" value="40960"></property> </bean>

3、form 添加 enctype="multipart/form-data"

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>上傳多個文件 實例</h2>  
    <form action="/upload/filesUpload" method="post"  enctype="multipart/form-data">  
        <p>選擇文件:<input type="file" name="files"></p>
        <p>選擇文件:<input type="file" name="files"></p>
        <p><input type="submit" value="提交"></p>
    </form>  
</body>
</html>

5、controller 部分

import java.io.File;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/upload")
public class UploadController {
    //通過Spring的autowired註解獲取spring默認配置的request  

    /*** 
     * 保存文件 
     * @param file 
     * @return 
     */  
    private boolean saveFile(MultipartFile file, String path) {  
        // 判斷文件是否為空  
        if (!file.isEmpty()) {  
            try {  
                File filepath = new File(path);
                if (!filepath.exists()) 
                    filepath.mkdirs();
                // 文件保存路徑  
                String savePath = path + file.getOriginalFilename();  
                // 轉存文件  
                file.transferTo(new File(savePath));  
                return true;  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return false;  
    }  

    @RequestMapping("/filesUpload")  
    public String filesUpload(@RequestParam("files") MultipartFile[] files) { 
        String path = "E:/upload/";
        //判斷file數組不能為空並且長度大於0  
        if(files!=null&&files.length>0){  
            //循環獲取file數組中得文件  
            for(int i = 0;i<files.length;i++){  
                MultipartFile file = files[i];  
                //保存文件  
                saveFile(file, path);  
            }  
        }  
        // 重定向  
        return "redirect:/list.html";  
    }  

}

運行如下:

技術分享

springMVC實現 MultipartFile 多文件上傳