上传图片:
@ApiOperation("上传图片")
@PostMapping("/uploadImage")
@ResponseBody
public ResultData uploadImage(@RequestParam MultipartFile multipartFile) {
if (multipartFile.isEmpty()) {
throw new BDException("请选择图片");
}
String fileType = multipartFile.getContentType();
logger.info("文件类型:" + fileType);
boolean flag = false;
for (String type : uploadImageTypes) {
if (fileType.equals(type)) {
flag = true;
break;
}
}
if (!flag) {
throw new BDException("请选择 png、jpg、jpeg、gif、bmp 格式的图片");
}
double imageSize = (double) multipartFile.getSize() / 1024 / 1024;
NumberFormat nf = new DecimalFormat("0.00");
logger.info("图片大小:" + Double.parseDouble(nf.format(imageSize)) + "M");
if (imageSize > uploadImageSize) {
throw new BDException("请上传" + uploadImageSize + "M以内图片");
}
String fileName = multipartFile.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM");
String format = simpleDateFormat.format(new Date());
String path = "D:/slkjImage/news" + "/" + format;
fileName = UUID.randomUUID() + suffixName;
String imageUrl = path + "/" + fileName;
logger.info("图片URL:" + imageUrl);
File dest = new File(imageUrl);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
multipartFile.transferTo(dest);
return ResultDataUtils.success("上传成功", imageUrl);
} catch (IOException e) {
}
return ResultDataUtils.fail("上传失败");
}
获取图片
@ApiOperation("获取图片")
@GetMapping("/getImage")
@ResponseBody
public void getImage(@RequestParam String imageUrl, HttpServletResponse response) {
if (imageUrl != null) {
logger.info("请求的图片URL:" + imageUrl);
FileInputStream in = null;
OutputStream out = null;
try {
File file = new File(imageUrl);
if (!file.exists()) {
throw new BDException("图片不存在");
}
in = new FileInputStream(imageUrl);
int i = in.available();
byte[] buffer = new byte[i];
in.read(buffer);
response.setContentType("image/jpeg");
response.setCharacterEncoding("utf-8");
out = response.getOutputStream();
out.write(buffer);
} catch (Exception e) {
throw new BDException("网络错误");
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
throw new BDException("网络错误");
}
}
}
}