MultipartFile上传

springMVC实现 MultipartFile 多文件上传

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

复制代码
     <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.4version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.1version>
        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 heretitle>
head>
<body>
    <h2>上传多个文件 实例h2>  
    <form action="/upload/filesUpload" method="post"  enctype="multipart/form-data">  
        <p>选择文件:<input type="file" name="files">

<p>选择文件:<input type="file" name="files">

<p><input type="submit" value="提交">

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){  
                MultipartFile file = files[i];  
                //保存文件  
                saveFile(file, path);  
            }  
        }  
        // 重定向  
        return "redirect:/list.html";  
    }  

}
复制代码

 

运行如下:

MultipartFile上传_第1张图片



https://www.cnblogs.com/linnuo/p/7805334.html

 

你可能感兴趣的:(MultipartFile上传)