Spring MVC上传文件的三种方式:
- 流
- MultipartFile
- CommonsMultipartResolver
servlet的文件上传参考servlet文件上传。
1. 必要的配置⚓
它们也使用了commons-fileupload
,所以同样需要导入此包:
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
都需要配置CommonsMultipartResolver
:
<!-- 多部分文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!--100MB-->
<property name="maxUploadSize" value="104857600" />
<!--4KB-->
<property name="maxInMemorySize" value="4096" />
<!--10MB-->
<property name="maxUploadSizePerFile" value="10485760"/>
</bean>
html页面:
<form action="/blog/blog/UploadFile1" method="post" enctype="multipart/form-data">
文件上传
<input type="file" name="any"><br>
<button type="submit">上传</button>
</form>
2. 流⚓
/**
* 以流的方式上传文件
* @param multipartFile 文件
*/
@PostMapping("/UploadFile1")
public Result uplodFile1(@RequestParam("any") MultipartFile multipartFile) {
FileOutputStream fo = null;
InputStream is = null;
boolean flag = false;
try {
ServletContext context = request.getServletContext();
String path = context.getRealPath("/WEB-INF/classes/files");
//输出流
fo = new FileOutputStream(path + File.separator + multipartFile.getOriginalFilename());
//输入流
is = multipartFile.getInputStream();
int len;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer)) != -1) {
fo.write(buffer, 0, len);
}
fo.flush();
flag = true;
}catch (IOException e){
e.printStackTrace();
}finally {
if (fo != null){
try {
fo.close();
}catch (IOException e){
System.out.println("close failed");
}
}
if (is != null){
try {
is.close();
}catch (IOException e){
System.out.println("close failed");
}
}
}
if (flag){
return new Result(StatusCode.SUCCESS, "上传成功");
}else {
return new Result(StatusCode.FAILED, "上传失败");
}
}
3. MultipartFile⚓
/**
* file.transferTo 保存
*/
@PostMapping("/UploadFile2")
public Result uploadFile2(@RequestParam("any") MultipartFile multipartFile){
File file = new File("D:/logs/" + multipartFile.getOriginalFilename());
try {
multipartFile.transferTo(file);
}catch (IOException e){
e.printStackTrace();
return new Result(StatusCode.FAILED, "上传失败");
}
return new Result(StatusCode.SUCCESS, "上传成功");
}
4. CommonsMultipartResolver⚓
/**
* 采用spring提供的上传文件的方法
*/
@PostMapping("/UploadFile3")
public Result uploadFile3(HttpServletRequest request){
CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getServletContext());
if (!resolver.isMultipart(request)){
return new Result(StatusCode.FAILED, "上传内容类型错误");
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator<String> iterator = multipartRequest.getFileNames();
try {
while (iterator.hasNext()){
MultipartFile multipartFile = multipartRequest.getFile(iterator.next());
multipartFile.transferTo(new File("D:/logs/" + multipartFile.getOriginalFilename()));
}
}catch (IOException e){
e.printStackTrace();
return new Result(StatusCode.FAILED, "上传失败");
}
return new Result(StatusCode.SUCCESS, "上传成功");
}
5. 使用vue、axio上传文件⚓
<input type="file" id="blog" placeholder="选择文件"/>
<button @click="uploadBlog">上传博客</button>
uploadBlog: function () {
let file = document.getElementById('blog').files[0]
let param = new FormData()
param.append('any', file)
console.log(param.get('any'))
this.$axios.post('/api/blog/blog/UploadFile3', param, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}