The last article wrote: Based on maven image upload, this article will introduce how to display the uploaded image! (The picture I uploaded is in the E:\test\ folder) The specific code is as follows:
public static final String IMG_DIR = "E:"+File.separator+"test"+File.separator;
@RequestMapping("/getAvatar/{id}")
public void getAvatar(@PathVariable("id") String id, HttpSession session, HttpServletResponse response) {
FileInputStream fis = null;
ServletOutputStream outputStream = null;
User user1 = userService.selectById(id);
String imgName = user1.getAvatar();
if (imgName == null) {
imgName = IMG_DIR+"qq.jpg";
}
try {
File imgFile;
if (StringUtils.isNotEmpty(imgName)) {
outputStream = response.getOutputStream();
User user = (User) session.getAttribute("user");
imgFile = new File( imgName);
if (!imgFile.exists()) {
imgFile = new File(imgName);
}
} else {
imgFile = new File(imgName);
}
//System.out.println(imgFile);
fis = new FileInputStream(imgFile);
byte[] b = new byte[1024];
while ((fis.read(b)) != -1) {
outputStream.write(b);
}
} catch (IOException e) {
logger.error("{}", e);
} catch (Exception e) {
logger.error("{}", e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Please modify the specific logic and picture path and name according to your own storage path!