在controller中,添加对应的方法体:
@PostMapping("/upload")
@ResponseBody
public ApiRestResponse upload(HttpServletRequest httpServletRequest, @RequestParam("file")MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
// 截取.前面的文件名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
UUID uuid = UUID.randomUUID();
String newFileName = uuid.toString() + suffixName;
// 文件目录
File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
// 文件名,Constant是我定义的常量类,具体内容在后面
File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
if(!fileDirectory.exists()){
if (!fileDirectory.mkdir()) {
throw new PlatformException(PlatformExceptionEnum.MAKEIDR_FAILED);
}
}
try {
// 需要注意,当你在transferTo这个方法中传入了相对路径,该方法会自动为你拼接上一个默认的路径,会导致虽然保存成功,但是你却找不到该文件
file.transferTo(destFile);
}catch (IOException e){
e.printStackTrace();
}
try{
// 通过getHost方法回显,获得文件名
return ApiRestResponse.success(getHost(new URI(httpServletRequest.getRequestURI()+ "")) + "/files/" + newFileName);
}catch (URISyntaxException e) {
return ApiRestResponse.error(PlatformExceptionEnum.UPDATE_FAILED);
}
}
//回显方法
private URI getHost(URI uri){
URI effectiveURI;
try{
effectiveURI = new URI(uri.getScheme(),uri.getUserInfo(),uri.getHost(),uri.getPort(),null,null,null);
}catch( URISyntaxException e){
effectiveURI = null;
}
return effectiveURI;
}
Constant的内容,需要注意的是@Value("${file.upload.dir}")中$符号后的是一对{},这里我已经踩过坑了。
对应在application.properties中的配置是,需要注意的是从本地计算机中复制过来的地址样式会是D:\src\main...,需要把\改成/,才能被正常读取,否则用这个路径去保存是一定会找不到的。另外结尾也要记得加上/,因为代码中是直接将地址和文件名拼接在一起,然后保存的,所以需要加上/。

注意的是,代码中还没有包含对静态资源的映射,需要添加一个config实现,缺少这个会影响保存后的显示




![[已解决]问题:root.users.hdfs is not a leaf queue](https://img-blog.csdnimg.cn/img_convert/55eeeb99a2641ae5fdd538ffc37ee1a2.png)






![[linux]进程控制——进程终止](https://img-blog.csdnimg.cn/direct/95f741caccab4dcbaf279042dc9a6efa.png)







