1、提供供用户上传的用户界面 upload.html(src/main/resources/static/upload.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="fileUploadController" method="post" enctype="multipart/form-data">
springboot姓名:<input type="text" name="name"/> <br/>
springboot文件:<input type="file" name="file"/> <br/>
<input type="submit" value="提交 ">
</form>
</body>
</html>
注意事项:实现文件上传功能,必须是 method="post" enctype="multipart/form-data"
2、编写控制器(src/main/java/cn/yangdh/controller/FileUploadController.java)
/**
* SpringBoot文件上传
* 功能:SpringBoot整合SpringMVC,实现文件上传
*
* 需要:@RestController(新)
* @author *****
*
*/
//@Controller
@RestController //表示这个类下所有的方法的返回值都会做jason转换(即@Controller和@ResponseBody的复合体)
public class FileUploadController{
/*
* 处理文件上传
*/
@RequestMapping("/fileUploadController")
public Map<String, Object> fileUpload(MultipartFile file)throws Exception{
String fileName = file.getOriginalFilename();
System.out.println(fileName);//输出文件名称
file.transferTo(new File("C:\\Users\\*****\\AppData\\Local\\Temp\\test1\\"+fileName));
Map<String, Object> map = new HashMap<>();
map.put("fileName", fileName);
return map;
}
}
3、编写springboot启动类(/src/main/java/cn/yangdh/App.java)
/**
* SpringBoot文件上传
* @author *****
*
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
4、编写springboot的配置文件(/src/main/resources/application.properties)
spring.http.multipart.maxFileSize=200MB //设置单个上传文件的大小
spring.http.multipart.maxRequestSize=300MB //设置一次请求上传文件的总容量