springboot实现简单的图片上传
1. 创建配置类
/**
* @author flame
* @version 1.0.0
* @date 2020/12/13 13:35
*/
@Data
@ConfigurationProperties("portal.file")
public class FileConfig {
private List<String> imgList;
private String imgServerAddress;//图片访问地址
private String attachServerAddress;//附件访问地址
private String imageContent;//图片目录
private String attachContent;//附件目录
}
2. 配置文件中的自定义属性
portal:
file:
imgList:
- .jpg
- .png
imgServerAddress: http://image.flame.com/images/ #开发环境
attachServerAddress: http://image.flame.com/attachments/ #开发环境
imageContent: D:/document/multi_blog/images #开发环境
attachContent: D:/document/multi_blog/attachments #开发环境
3.创建Controller
/**
* 图片上传
*
* @param file 图片
* @return 视图对象
*/
@PostMapping("/uploadImg")
public Result uploadImg(@RequestBody MultipartFile file) {
String originalFilename = file.getOriginalFilename();
if (StringUtils.isBlank(originalFilename)) {
return new Result(StatusCode.FILE_IS_NULL);
}
String extensionName = originalFilename.substring(originalFilename.lastIndexOf("."));
if (!fileConfig.getImgList().contains(extensionName)) {
return new Result(StatusCode.IMAGES_SORT_ERROR);
}
String newFileName = new Date().getTime() + extensionName;
try {
file.transferTo(new File(fileConfig.getImageContent(), newFileName));
} catch (IOException e) {
return new Result(StatusCode.FILE_UPLOAD_FAIL);
}
//返回url
return new Result(StatusCode.OK, fileConfig.getImgServerAddress() + newFileName);
}