SpringMVC文件上传
1. 编写hello工程
1.1 导入依赖
导入apache提供的jar包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
1.2 配置spirngMVC配置文件
<!-- 文件上传配置 -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<!-- 最大上传限制100MB -->
<property name="maxUploadSize" value="104857600"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
1.3 编写测试jsp页面
form表单一定要加上 enctype=“multipart/form-data” 属性,还要为file添加name属性,否则会报错!
提交方式建议post,使用get提交会限制文件大小。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<p><input type="file" name="file1"></p>
<p><input type="submit" name="提交"></p>
</form>
</body>
</html>
1.4 编写测试接口
/**
* 将提交上来的文件封装为CommonsMultipartFile对象
* 批量上传:将CommonsMultipartFile设置为数组即可
*/
@PostMapping("/upload")
public void upload(@RequestParam("file1")CommonsMultipartFile file){
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
//获取文件名字
String filename = file.getOriginalFilename();
inputStream = file.getInputStream();
fileOutputStream = new FileOutputStream("/Users/sheepl/Downloads/"+UUID.randomUUID()+filename);
//文件读取
int readLength;
byte[] data = new byte[1024*1024];
while ((readLength = inputStream.read(data)) != -1){
fileOutputStream.write(data,0,readLength);
}
//刷新文件输出流
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
//关闭流前先判断是否为空,防止空指针
try {
if (inputStream != null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fileOutputStream != null){
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}