将 upload.html放在static下面是为了方便访问
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
文件上传<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
Controller控制层
@RestController
public class UploadContorller {
@PostMapping("/upload")
public Map multipart(MultipartFile file, HttpServletRequest request){//MultipartFile 表示你当前上传文件的对象
Map map = new HashMap();
// 拿到文件名
String name = file.getOriginalFilename();
// 换名字
String newNamae = new Date().getTime() + new Random().nextInt(999999) + name;
// 得到上传路径 真实的开发过程中,实际上是你的服务器路径 192.168.208.128/xxx/xxx
String path = request.getServletContext().getRealPath("/upload/");
//
File f = new File(path);
// 当前上传的这个服务器地址如果没有这个目录
if (!f.exists()) {
f.mkdir();//那我就创建这个目录
}
File f1 = new File(path+newNamae);
//显示路径地址
System.out.println(path+newNamae);
try {
file.transferTo(f1);
map.put("msg","上传成功");
}catch (IllegalStateException e){
e.printStackTrace();
map.put("msg","上传失败");
}catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
启动类 Bootdemo2Application
package org.zhx.bootdemo2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.util.unit.DataSize;
import javax.servlet.MultipartConfigElement;
@SpringBootApplication
public class Bootdemo2Application {
public static void main(String[] args) {
SpringApplication.run(Bootdemo2Application.class, args);
}
public MultipartConfigElement multipartConfigElement(){
MultipartConfigFactory factory = new MultipartConfigFactory();
//设置上传的文件大小
factory.setMaxFileSize(DataSize.parse("1024kb"));
//设置上传的总文件大小
factory.setMaxRequestSize(DataSize.parse("102400kb"));
//创建上传的配置
return factory.createMultipartConfig();
}
}
浏览器访问upload.html 并选择文件上传
上传成功