序言:利用MultipartFile接收前台传过来的文件保存到本地
1.pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
2.application.yml 配置上传文件大小限spring制
spring
servlet:
multipart:
#设置单个文件上传大小
max-file-size: 10MB
#设置总上传的数据大小
max-request-size: 50MB
3.html层
<html >
<head>
<meta charset="utf-8">
</head>
<body>
<form action="/test/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="提交上传"/>
</form>
</body>
</html>
3.controller层
package com.example.shop.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* com.example.uploadfile.controller
* 红烛
* 介绍:
*/
@Controller
@RequestMapping(value={"test"})
public class UploadController {
/**
* 初始化上传文件界面,跳转到index.html
*/
@RequestMapping(value="/index",method = RequestMethod.GET)
public String index(){
return "index";
}
/**
* 上传文件方法
*/
@RequestMapping(value="/upload",method = RequestMethod.POST)
public @ResponseBody String upload(HttpServletRequest request,MultipartFile file){
try {
//生成uuid
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//得到上传时的文件名
String filename=file.getOriginalFilename();
//上传目录地址
//1.1保存到项目指定目录
String uploadDir="C:\\Users\\21112\\Documents\\我的资源\\idea\\shop\\src\\main\\resources\\static\\upload";
//1.2 上传到相对路径 request.getSession().getServletContext().getRealPath("/")+"upload/";
//1.2 此路径为tomcat下,可以输出看一看
//如果目录不存在,自动创建文件夹
File dir=new File(uploadDir);
if(!dir.exists()){
dir.mkdir();
}
//保存文件对象 加上uuid是为了防止文件重名
File serverFile=new File(uploadDir+"\\"+uuid+filename);
file.transferTo(serverFile);
} catch (Exception e) {
//打印错误堆栈信息
e.printStackTrace();
return "上传失败";
}
return "上传成功";
}
}
4.效果图