html代码实例:
<form method="post" enctype="multipart/form-data" action="upload.do">
<p>请选择要上传的文件:</p>
<p><input type="file" name="file" /></p>
<p><input type="submit" value="上传" /></p>
</form>
<!--以上代码中,`<form>`的`method`属性值必须是`post`,`enctype`属性值必须是`multipart/form-data`,且上传控件的`type`属性值必须是`file`。-->
如果上传的文件的定位是相同的,且数量不固定,则在客户端使用控件,添加`multiple="multiple`属性,即:
<input type="file" name="file" multiple="multiple" />
然后,在服务器端的控制器中,将参数声明为`MultipartFile[]`即可。
1.在项目中导入Jar包:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
2.在Spring配置文件中添加CommonsMultipartResolver配置:
maxUploadSize:最大上传的数据量,以字节为单位,假设设置为10M,则单次请求的最大数据就是10M,可能这次上传过程中有2个文件,则2个文件的总和不允许超过10M;
maxUploadSizePerFile:上传的每个文件的最大大小,假设设置为10M,且这次上传过程中有2个文件,则每个文件都不可以超过10M,但是这次请求的数据总大小可能接近20M;
defaultEncoding:默认字符集,用于设置上传时同一个表单中可能提交的其它字符的编码。
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
<!--在配置时,必须指定`id`,且值必须是`multipartResolver`。-->
3.在处理请求的方法中,添加`MultipartFile file`参数,该参数就是用户上传的文件的数据,并在参数之前添加@RequestParam注解:
void transferTo(File dest) | 将文件写入到dest所代表的文件 |
---|---|
boolean isEmpty() | 判断是否为空文件 (未选择任何文件或文件内容为0字节) |
long getSize() | 获取文件字节长度 |
String getContentType() | 或取文件类型 (image/png) |
String getOriginalFilename() | 获取上传时的文件名 (xxx.png) |
4.最后,调用参数对象的`void transferTo(File dest)`方法即可将用户上传的文件保存到服务器的硬盘中!
为了避免文件被覆盖,每个文件的路径或文件名应该不发生冲突,例如可以使用唯一的文件名,要保证文件名唯一,可以考虑使用时间、随机数等数据作为文件名的一部分,也可以使用用户的唯一数据,例如用户的id、用户名等作为文件名的一部分,具体规则可自行决定。
@RequestMapping("upload.do")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file,
HttpServletRequest request)
throws IllegalStateException, IOException {
System.out.println("UploadController.upload()");
// 判断上传的文件是否为空
boolean isEmpty = file.isEmpty();
System.out.println("\tisEmpty=" + isEmpty);
if (isEmpty) {
throw new RuntimeException("上传失败!上传的文件为空!");
}
// 检查文件大小
long fileSize = file.getSize();
System.out.println("\tsize=" + fileSize);
if (fileSize > 1 * 1024 * 1024) {
throw new RuntimeException("上传失败!上传的文件大小超出了限制!");
}
// 检查文件MIME类型
String contentType = file.getContentType();
System.out.println("\tcontentType=" + contentType);
List<String> types = new ArrayList<String>();
types.add("image/jpeg");
types.add("image/png");
types.add("image/gif");
if (!types.contains(contentType)) {
throw new RuntimeException("上传失败!不允许上传此类型的文件!");
}
// 准备文件夹,获取项目中upload文件夹的路径
String parentDir = request.getServletContext().getRealPath("upload");
// request.getSession().getServletContext().getRealPath("");
// request.getRealPath("");
System.out.println("\tpath=" + parentDir);
File parent = new File(parentDir);
if (!parent.exists()) {
parent.mkdirs();
}
// 获取原始文件名
String originalFilename = file.getOriginalFilename();
System.out.println("\toriginalFilename=" + originalFilename);
// 确定最终保存时使用的文件
String filename = UUID.randomUUID().toString();
String suffix = "";
int beginIndex = originalFilename.lastIndexOf(".");
if (beginIndex != -1) {
suffix = originalFilename.substring(beginIndex);
}
// 执行保存文件
File dest = new File(parent, filename + suffix);
file.transferTo(dest);
return "OK";
}
在SpringBoot中不需要导包,并且SpringBoot中默认配置了上传文件不能超过1MB
修改方式有两种
方式一:通过application.properties文件配置
//适用SpringBoot2.0后的版本
spring.servlet.multipart.max-file-size = 10MB
spring.servlet.multipart.max-request-size=100MB
//适用SpringBoot1.4之后2.0之前
spring.http.multipart.maxFileSize = 10MB
spring.http.multipart.maxRequestSize=100MB
//适用SpringBoot1.4之前
multipart.maxFileSize = 10MB
multipart.maxRequestSize=100MB
方式二:在启动类中配置Bean来设置文件大小
现在在启动类之前添加@Configuration注解,然后在类中添加如下方法:
@Bean
public MultipartConfigElement getMultipartConfigElement() {
//创建工厂
MultipartConfigFactory factory = new MultipartConfigFactory();
//创建单个文件最大限制参数.ofMegabytes单位MB,另有KB,GB,TB可供选择
DataSize maxFileSize = DataSize.ofMegabytes(200);
//将参数设置到工厂中
factory.setMaxFileSize(maxFileSize);
//创建单次上传最大文件限制参数
DataSize maxRequestSize = DataSize.ofMegabytes(500);
//将参数设置到工厂中
factory.setMaxRequestSize(maxRequestSize);
//从工厂中获取配置好的对象
return factory.createMultipartConfig();
}