Reputation: 133
I use Spring MVC and JPA in my project. I get file as byte[]
and save in Database. But when I want to display in <img>
tag of HTML it doesn't get displayed.
My entity is:
class Photo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
@Lob
private byte[] profilePic;
// getter and setter
}
Value in the Database is:
{
"id": 4,
"title": "pic 1",
"profilePic": "ZGF0YTppb...VFtQ0M=",
}
And this is how I try to display the image in HTML:
<img src='ZGF0YTppb...VFtQ0M=' />
//or
<img src='data:image/jpeg;base64,ZGF0YTppb...VFtQ0M=' />
What to do to display the photo?
Thanks.
Upvotes: 1
Views: 1420
Reputation: 33
HTML:
<img id="profileImg" src="">
JS:
document.getElementById("profileImg").src = "data:image/png;base64," + profilePic;
This assumes that your image is stored in PNG format (and base64 encoded). For other image format (JPEG, etc.), you need to change the MIME type ("image/..." part) in the URL.
Upvotes: 0
Reputation: 5442
Assuming it's base64 encoded:
<img src='data:image/jpeg;base64,ZGF0YTppb...VFtQ0M=' />
Basically you can use data urls with this format depending on what content [type] you want to display:
data:[<mime type>][;charset=<charset>][;base64],<encoded data>
Upvotes: 2