以下内容都是工作中组长他们常用的形式
import org.springframework.web.multipart.MultipartFile;
//需要上面的包
@PostMapping("/uploadImg")
@Transactional
public CommonResult uploadImg(@RequestParam("file") MultipartFile file,@RequestParam("id") Integer id){
if(file.isEmpty()){
return CommonResult.failed("文件上传失败,请重新上传");
}
MmsTemplate temp = mmsTemplateService.selectById(id);
if(temp == null){
return CommonResult.failed("没有找到该模板");
}
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
Integer code = ImgTypeEnum.getCodeByMessage(suffix.replace(".",""));
if(null == code){
return CommonResult.failed("上传的文件格式不正确,请上传正确的图片格式");
}
String fileName = UUID.randomUUID().toString()+suffix;
String filePath = "D://img//";
//需要限定上传图片的格式
File dest = new File(filePath+fileName);
try {
//上传文件并将文件地址与模板绑定
file.transferTo(dest);
log.info("上传成功");
String realPath = dest.getAbsolutePath();
Map<String,String> result = new HashMap<String, String>();
result.put("path", realPath);
result.put("fileName", fileName);
//设置图片地址
temp.setImgUrl(realPath);
mmsTemplateService.update(temp);
return CommonResult.success(result,"上传图片成功!");
} catch (IOException e) {
e.printStackTrace();
return CommonResult.failed("上传图片失败!");
}
}
主要采用的是SpringMvc自带的transferTo方法将文件上传,然后记录图片地址并将图片地址保存在数据库中。其中判断上传文件是否为图片的方法使用的是ImgTypeEnum的枚举类,具体代码如下:
public enum ImgTypeEnum {
JPEG(0,"jpeg"),
JPG(1,"jpg"),
PNG(2,"png"),
TIF(3,"tif"),
GIF(4,"gif"),
WEBP(5,"webp"),
BMP(6,"bmp");
private Integer code;
private String message;
ImgTypeEnum(int code,String message){
this.code = code;
this.message = message;
}
public Integer getCode(){
return code;
}
public String getMessage(){
return message;
}
public static String getMessageByCode(Integer code){
for (ImgTypeEnum value : ImgTypeEnum.values()) {
if(value.getCode().equals(code)){
return value.getMessage();
}
}
return null;
}
public static Integer getCodeByMessage(String message){
for (ImgTypeEnum value : ImgTypeEnum.values()) {
if(value.getMessage().equals(message)){
return value.getCode();
}
}
return null;
}
}
通过两个枚举类中写的静态方法就可以判断当前类型是否在其中。