/**
* 上传文件的方法
*
* @param file
* @return
* @throws IOException
*/
@PostMapping("/upload")
public R<Map<String, String>> upload(@RequestParam("file") MultipartFile file) throws IOException {
Map<String, String> resMap = new HashMap<>();
//文件判空
if (file.isEmpty()) {
resMap.put("Error", "400" + "File Not Exists");
return R.ok(resMap);
}
//获取文件名称
String ori_name = file.getOriginalFilename();
//需要改变文件名称需要加上文件类型oldName.substring(ori_name.lastIndexOf(".")+1)
//获取当前时间戳
long time = System.currentTimeMillis();
String cur_name = time + "." + ori_name.substring(ori_name.lastIndexOf(".") + 1);
String path = ordinaryPath + File.separator + cur_name;
//创建文件对象
File curr_file = new File(path);
//获取文件目录判断是否存在
if (!curr_file.getParentFile().exists()) {
//确保创建文件时目标文件夹存在
curr_file.getParentFile().mkdirs();
}
try {
//存储
file.transferTo(curr_file);
} catch (IOException e) {
e.printStackTrace();
resMap.put("Error", "500" + "transferTo err");
return R.ok(resMap);
}
resMap.put("path", path);
resMap.put("name", ori_name);
return R.ok(resMap);
}
JAVA实现文件上传
于 2022-01-21 10:39:36 首次发布