使用Spring boot上传文件
1、首先要导入依赖web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、编写上传的测试页面
<h3>上传单个文件</h3>
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file" required><br>
<input type="submit" value="上传单个文件">
</form>
3、在yml文件中配置上传文件的大小
servlet:
multipart:
max-file-size: 100MB #单个文件上传最大值
4、编写接口
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
public class UpLoadController {
@PostMapping("/upload")
public Object upload(@RequestParam("file") MultipartFile file){
return saveFile(file);
}
private Object saveFile(MultipartFile file){
if (file.isEmpty()){
return "未选择文件";
}
String filename = file.getOriginalFilename(); //获取上传文件原来的名称
String filePath = "F:\\Work\\LuxaingJsp\\src\\main\\resources\\static\\video\\";
File temp = new File(filePath);
if (!temp.exists()){
temp.mkdirs();
}
File localFile = new File(filePath+filename);
try {
file.transferTo(localFile); //把上传的文件保存至本地
System.out.println(file.getOriginalFilename()+" 上传成功");
}catch (IOException e){
e.printStackTrace();
return "上传失败";
}
return "ok";
}
}
上传文件必须是post请求方式