I am using the following snippet to select and read images from file:
<div class="col-md-6 form-group">
<input type='file' name="image" onchange="readURL(this);"
class="form-control" />
<img id="userimg" src="#" alt="" />
</div>
.js:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#userimg')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
In my servlet I convert the file to a byte[]:
(request.getParameter("image")).getBytes()
and insert it into a database.
Then, I try to read it from the database and display in a .jsp page, like this:
.jsp
<div class="panel panel-success">
<h2>Pictures</h2>
<%
List<byte[]> pics = PictureTable.getConcertPictures(concertBean.getId());
%>
<%
for (byte[] p : pics) {
String encoded = ImageHelper.encodeImage(p);
%>
<img src="data:image/jpg;base64,<%=encoded%>">
<%
}
%>
</div>
ImageHelper.java:
public static String encodeImage(byte[] img) {
return Base64.encode(img);
}
but the image is not displayed correctly (something does get inserted into the database).
Edit:
I've modified my code:
.jsp:
<div class="comments">
<div class="panel panel-success">
<h2>Pictures</h2>
<%
List<byte[]> pics = PictureTable.getConcertPictures(concertBean.getId());
%>
<%
for (byte[] p : pics) {
String encoded = ImageHelper.encodeImage(p);
%>
<img src="data:image/jpg;base64,<%=encoded%>">
<%
}
%>
</div>
<!-- /container -->
<form
action="GalleryController?action=add_concert_picture&concertID=<%=concertBean.getId()%>"
method="post" class="panel panel-success"
enctype="multipart/form-data">
<div class="col-md-6 form-group">
<input type='file' name="image" class="form-control" />
</div>
<button type="submit" class="btn">Submit</button>
</form>
</div>
servlet:
Part filePart = request.getPart("image");
InputStream fileContent = filePart.getInputStream();
PictureTable.insertConcertPicture(cid, user.getUser().getId(), fileContent);
PictureTable.java:
public static void insertConcertPicture(int concertId, int userId, InputStream photo) {
try (Connection connection = ConnectionPool.getConnectionPool().checkOut()) {
PreparedStatement ps = connection
.prepareStatement("INSERT INTO concertphototable(ConcertId, UserId, Photo) VALUES(?,?,?)");
...
ps.setBinaryStream(3, photo);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
The image is still not shown correctly, but now the "submit" part of the page is not even visible.
imgtag url directly to that servlet?Base64.getEncoder().encode(img)? Also did you check that your images are in JPEG?encode(img)returned, and got the name of my file.src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAAAAAAAD/4Zf2RXhpZgAATU0AKgAAAAg...this goes on for veeeeeeery long. After that, there is the code for the submit button.