前端
<a href="${pageContext.request.contextPath}/goods/attachment/${g.id}">下载图片</a> |
<a href="${pageContext.request.contextPath}/goods/inline/${g.id}">预览图片</a> |
后端
controller层
@Value("${uploadPath}")
private String filePath;
@GetMapping("/goods/{downType:attachment|inline}/{id:\\d+}")
public HttpEntity downloadImg(@PathVariable String downType,@PathVariable Integer id){
Map<String,Object> img = goodsService.queryGoodsImgById(id,filePath);
return ResponseEntity.status(HttpStatus.OK)
.contentType(MediaType.IMAGE_JPEG)
//attachment下载inline预览
.header("Content-Disposition",downType+";filename=" + img.get("name"))
.body(img.get("data"));
}
service层
@Override
public Map<String, Object> queryGoodsImgById(Integer id,String filePath) {
String img = mapper.findGoodsImgById(id);
File file = new File(filePath, img);
Map<String,Object> map = new HashMap<>();
map.put("name",img);
try {
byte[] bytes = FileUtils.readFileToByteArray(file);
map.put("data",bytes);
} catch (IOException e) {
e.printStackTrace();
}
return map;
}