使用Apache Commons FileUpload,我们可以配置一个名为
multipartResolver的CommonsMultipartResolver类型的bean。还需要将
commons-fileupload作为classpath的依赖项。
<dependency>
<groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
配置文件增加:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小上限,单位为字节(10MB) -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
目录
单文件上传控制器
package com.wdzl.controller;
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 java.io.File;
import java.io.IOException;
@Controller
@RequestMapping(value = "/many-file-upload")
public class ManyFileUploadController {
@RequestMapping("/fileupload")
public String fileUpLoad(
@RequestParam("desc") String[] desc,
@RequestParam("file") MultipartFile[] file
) {
try {
for (MultipartFile multipartFile : file) {
//存放到D盘一级目录
multipartFile.transferTo(new File("D:\\"
+ multipartFile.getOriginalFilename()));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//上传完成,返回成功页面
return "upload-success";
}
}
先进入这个页面
浏览上传文件通过控制器controller 控制,将文件上传到D盘;
多文件上传控制器
package com.wdzl.controller;
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 java.io.File;
import java.io.IOException;
@Controller
@RequestMapping(value = "/many-file-upload")
public class ManyFileUploadController {
@RequestMapping("/fileupload")
public String fileUpLoad(
// 跟一个文件上传一样,就是这里用来数组
@RequestParam("desc") String[] desc,
@RequestParam("file") MultipartFile[] file
) {
try {
for (MultipartFile multipartFile : file) {
multipartFile.transferTo(new File("D:\\"
+ multipartFile.getOriginalFilename()));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "upload-success";
}
}
先进入这个页面
Servlet Part 的方法再servlet阶段学过
1.
2.