springMVC实现 MultipartFile 多文件上传

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、配置Sping配置文件

<!-- 配置文件解析器 -->
    <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、jsp页面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>

4、controller类

package com.hwua.controller;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
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;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RequestMapping("/user")
@Controller
public class FileController {
   @RequestMapping(
"/upload") public ModelAndView fileUpload(HttpServletRequest request,@RequestParam MultipartFile[] upload) throws IOException { ModelAndView mv = new ModelAndView(); String path=request.getServletContext().getRealPath("/"); File file =new File(path); if (!file.exists()){ file.mkdirs(); }
     
if (upload!=null&&upload.length>0){ for (int i=0;i<upload.length;i++){ String filename = upload[i].getOriginalFilename(); String uuid = UUID.randomUUID().toString().toUpperCase(); filename = uuid+"_"+filename; upload[i].transferTo(new File(file,filename)); mv.addObject("info","上传成功!"); mv.setViewName("success"); } } return mv; } }
原文地址:https://www.cnblogs.com/wzming0730/p/11077747.html