- @RequestParam(“file”) MultipartFile file
将请求参数绑定到你控制器的方法参数上 file是指前端上传input的name的值 - MultipartFile 类
用来接收前端传来的文件 - ResourceUtils类
ResourceUtils 工具类,支持“classpath:”和“file:”的地址前缀,能够从指定的地址加载文件资源
通过ResourceUtils.getURL(“classpath:”).getPath()可以获取到路径
方法 | 区别 |
---|---|
getPath() | 获取file的路径,如果默认为相对路径则返回相对路径 |
getAbsolutePath() | 获取全路径,如果构造的时候试相对路径,返回当前目录的路径+构造file时候的路径 |
- 根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
File(String parent, String child)
- transferTo()方法
因为文件流只可以接收读取一次,传输完毕则关闭流;
在文件上传的时候,MultipartFile中的transferTo(dest)方法只能使用一次;
并且使用transferTo方法之后不可以在使用getInputStream()方法;
否则再使用getInputStream()方法会报异常
使用transferTo(dest)方法将上传文件写到服务器上指定的文件;
controller类:
@PostMapping("/product/upload")
public Result upload(@RequestParam("file") MultipartFile file){
try {
File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
System.out.println("地址:"+projectPath);
File upload = new File(projectPath.getAbsolutePath(),"static/img/product");
if(!upload.exists()){
upload.mkdirs();
}
Result result = null;
if(file.isEmpty()){
result = ResultUtils.error(-1,"上传失败");
}
String fileName = file.getOriginalFilename();
File dest = new File(upload.getAbsolutePath()+File.separator+fileName);
file.transferTo(dest);
Map<String,String> map=new HashMap<String,String>();
map.put("src",fileName);
result = ResultUtils.success(map);
result.setCode(0);
}catch (Exception e){
}
return ResultUtils.error(-1,"上传失败");
}