pre
public Boolean uploadAvatarByDefaultImage(AccountEntity user) {
ResponseBody responseInfo = null;
try {
String index=user.getExtensionLink()[0].getExtension().substring(2);
File photo = new File("./avatar/"+index+".png");
String name = "image";
String fileName = "user_avatar.png";
String mediaType = "image/png";
BufferedImage bufferedImage = ImageIO.read(photo);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", bos);
byte[] fileContent = bos.toByteArray();
## responseInfo = setting avatar function ##
return responseInfo.contentLength() == (-1);
} catch (NoSuchFileException e) {
logger.error("not avatar file", e);
} catch (IOException | RestException e) {
logger.error("failed to upload avatar", e);
} finally {
if (responseInfo != null) {
responseInfo.close();
}
}
return false;
}
很早以前实现的一个用来更新账号头像的方法,当时没有注意在docker跑的时候会失败
问题点在于以前是直接去load一个文件,但是在docker跑的时候,已经打包成一个jar包,直接load是没办法去获取的
把图片文件放在resources目录下,就可以使用java的load resources的方法去读取文件
网上给的方法是
1. BufferedImage im = ImageIO.read(new File(getClass().getResource(fileName).toURI()));
这种方法没办法读取到文件
2. BufferedImage buff =ImageIO.read(getClass().getResourceAsStream(fileName));
这种方法是OK的
也可以使用java封装好的类ClassPathResource
ClassPathResource resource = new ClassPathResource(pngPath);
filePath: /avatar 即可
after
public Boolean uploadAvatarByDefaultImage(AccountEntity user) {
ResponseBody responseInfo = null;
try {
String index=user.getExtensionLink()[0].getExtension().substring(2);
String name = "image";
String fileName = "user_avatar.png";
String mediaType = "image/png";
String pngPath = "/avatar/" + index + ".png";
ClassPathResource resource = new ClassPathResource(pngPath);
BufferedImage bufferedImage = ImageIO.read(resource.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", bos);
byte[] fileContent = bos.toByteArray();
## responseInfo = setting avatar function ##
bos.close(); #只要是stream类型都需要close
return responseInfo.contentLength() == (-1);
} catch (NoSuchFileException e) {
logger.error("not avatar file", e);
} catch (IOException | RestException e) {
logger.error("failed to upload avatar", e);
} finally {
if (responseInfo != null) {
responseInfo.close();
}
}
return false;
}