java 上传图片
//application.yml中配置path和prefix
//上传图片的地址
@Value(value = "${uploadfilepath}")
private String uploadFilePath;
//图片的前缀eg:http:127.0.0.1:8080/manage_image
@Value(value = "${imageUrlPrefix}")
private String imageUrlPrefix;
@PostMapping(value = "/addPic")
public ReturnWrapper<String> upload(@RequestParam("file") MultipartFile imgFile) {
if (imgFile.isEmpty()) {
return ReturnWrapMapper.ok("文件不能为空");
}
//原始文件名
String originalFilename = imgFile.getOriginalFilename();
//计算后缀有几位 .jpg
int i = imgFile.getOriginalFilename().lastIndexOf(".");
//截取后四位是文件的格式
String substring = originalFilename.substring(i);
//生成文件唯一标识名称
String filename = UniqueID.nextId(substring);
try {
File newFile = new File(uploadFilePath + filename);
imgFile.transferTo(newFile);
} catch (IOException e) {
return ReturnWrapMapper.error(ReturnCode.FILE_UPLOAD_ERROR);
}
//上传的位置http:127.0.0.1:8080/manage_image/123.jpg
String imgUrl = imageUrlPrefix + filename;
return ReturnWrapMapper.ok(imgUrl);
}
}