개발/Java
[JAVA] DB 에서 파일 경로 불러와 화면에 이미지 출력
버물버물리
2020. 9. 27. 04:45
DB에서 파일경로를 가져와 Base64 로 인코딩하여 화면에서 이미지를 출력하는 예제이다.
FileUtil.java
public static byte[] convertFileContentToBlob (String filePath) {
byte[] result = null;
try {
result = FileUtils.readFileToByteArray( new File(filePath));
} catch (IOException ie) {
log.error("file convert Error");
}
return result;
}
public static String convertBlobToBase64 (byte[] blob) {
return new String(Base64.getEncoder().encode(blob));
}
public static String getFileContent (String filePath) {
byte[] filebyte = convertFileContentToBlob(filePath);
return convertBlobToBase64(filebyte);
}
위처럼 FileUtils.readFileToByteArray 를 사용하려면 org.apache.commons.io 를 maven 또는 gradle 에 추가하여야 한다.
main.java
String filePath = vo.getFilePath(); //DB에서 조회한 파일경로
String fileContent = FileUtil.getFileContent(filePath);
model.addAttribute("fileContent", fileContent);
javascript
$(document).ready( function () {
var fileContent = "${fileContent}"
document.getElementById("imagePreview").src = "data:image/png;base64," + fileContent;
})
참조
stackoverflow.com/questions/2418485/how-do-i-convert-a-byte-array-to-base64-in-java
How do I convert a byte array to Base64 in Java?
Okay, I know how to do it in C#. It's as simple as: Convert.ToBase64String(byte[]) and Convert.FromBase64String(string) to get byte[] back. How can I do this in Java?
stackoverflow.com