I'm trying to display an uploaded picture (which is now a byte array) on a jsp page. Now, the byte[] column exists in the database and has to be converted to an image.
This is what I've been trying:
Part of the table on jsp page:
<c:forEach var="user" items="${userList}">
<tr>
<td>${user.fileName}</td>
<td>
<img src="data:image/jpg;base64,${user.imageFile}" alt="No image">
</td>
Part of the controller that takes an array of bytes from a MultipartFile object:
#RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView userRegister(#ModelAttribute("user") #Valid User user, BindingResult result, ModelMap model, #RequestParam("fileData") MultipartFile fileData) throws Exception {
if (!fileData.isEmpty() && fileData != null) {
byte[] bytes = fileData.getBytes();
user.setFileName(fileData.getOriginalFilename());
user.setImageFile(bytes);
}
}
If any additional information is needed, please let me know. Thanks.
You can add a tranisent base64imageFile property to your User. It will hold the base64 encoded string of the image, which you can access in your jsp like
<img alt="img" src="data:image/jpeg;base64,${user.base64imageFile}"/>
And in your method you should do the encoding, somethig like
#RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView userRegister(#ModelAttribute("user") #Valid User user, BindingResult result, ModelMap model, #RequestParam("fileData") MultipartFile fileData) throws Exception {
if (!fileData.isEmpty() && fileData != null) {
byte[] bytes = fileData.getBytes();
user.setFileName(fileData.getOriginalFilename());
user.setImageFile(bytes);
byte[] encodeBase64 = Base64.encodeBase64(bytes);
String base64Encoded = new String(encodeBase64, "UTF-8");
user.setBase64image(base64encoded);
}
}
IOUtils and Base64 are a handy util classes from org.apache.commons, shouldn't have a problem finding
Related
I have a method in my controller that directs to the page with comments.
All comments are related to a specific message. I use pathvariable to send messageID that I later use to get comments from my database.
#GetMapping("/showComments/{messageId}")
public String displayComments(#PathVariable Long messageId, #AuthenticationPrincipal User user, Model model) {
List<Comment> comments = commentService.showComments(messageId);
Message messageGotById = messageService.getMessageById(messageId);
model.addAttribute("comments", comments);
model.addAttribute("messageGot",messageGotById);
model.addAttribute("userId",user.getId());
return "listComments";
}
And then I have a method for fetching images from database
#GetMapping("/getImageComment/{id}")
public void showCommentImage(#PathVariable Long id, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
Message messageImage = messageService.getMessageById(id);
ImageInfo imageInfo = messageImage.getUsr().getImageInfo();
byte[] imageData = imageInfo.getImageData();
String encode = Base64.getEncoder().encodeToString(imageData);
InputStream is = new ByteArrayInputStream(imageData);
IOUtils.copy(is, response.getOutputStream());
}
listComments.html
<img th:src="#{'getImageComment/' + ${userId}}" height="55"
width="55">
Added the link I use to go to listComments.html
<a th:href="#{/showComments/{id}(id=${message.id})}">comment</a>
The issue here is that when there is a variable on URI in displayComments method, images are not displayed.
But without pathvariable everything works just fine.I cant understand what is the problem.
Followed dsp_user advice and used Server-relative URLs. Changed
<img th:src="#{'getImageComment/' + ${userId}}" height="55"
width="55">
to
<img class="rounded" th:src="#{'~/getImageComment/' + ${userId}}" height="55"
width="55">
And It finally worked for me.
i'm trying to upload an image in the database and then show it on a jsp, in a web application developed with spring MVC.
I've read all the questions concerning to this problem but i didn't get it.
I was thinking about saving the image in a blob field, instead of a clob one. Is it a good idea?
I've created a multipart form with a file input.
<form:form method="POST" action="monorigineEdit" modelAttribute="formMonorigineEdit" enctype="multipart/form-data">
...
<input type="file" name="image">
...
</form:form>
In the controller i get correctly the Multipartfile in this way
public String monorigineEdit(#RequestParam("image") MultipartFile file, HttpServletRequest request, ModelMap model,
#ModelAttribute(value = "formMonorigineEdit") #Valid MonorigineDTO monorigineDTO, BindingResult result, RedirectAttributes redirectAttrs) throws FacadeException
I would like, for testing purpose, just to forward the image to a jsp in base64 and show it, in this way in the controller
...
File auxFile = multipartToFile(file);
FileInputStream fi = new FileInputStream(auxFile);
byte[] byteArrayImage = Base64.encodeBase64(IOUtils.toByteArray(fi));
model.put("myImage", byteArrayImage);
return new String("monorigineEditTemplate");
and with this tag in the jsp
<img id="myImg" name="myImg" src="data:image/jpeg;base64,<c:out value='${myImage}'/>" >
The method multipartToFile is this one:
public File multipartToFile(MultipartFile multipart) throws IllegalStateException, IOException
{
File convFile = new File(multipart.getOriginalFilename());
multipart.transferTo(convFile);
return convFile;
}
The problem is that the browser doesn't show the image, but i can't get where i'm wrong.
Can you help me? :)
Thanks a lot.
Here is how you convert image to String and display it :
import org.apache.commons.codec.binary.Base64;
public String convertByteArrayImagetoString(){
BASE64Encoder base64Encoder = new BASE64Encoder();
File imagePath = new File(defaultPersonImagePath);
try {
BufferedImage bufferedImage = ImageIO.read(imagePath);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
photoString = "data:image/png;base64," + base64Encoder.encode(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
if you have doubts, let me know.
I'm trying to display an image in jsp injected.
I upload and I store the image in the database, but do not know how retrieve and display in jsp.
My controller:
#RequestMapping(value = "/ver2", method = RequestMethod.GET)
public void ver2(HttpSession session, HttpServletResponse response) {
OutputStream oImage;
Item item10 = itemRepository.findOne(11);
try {
byte[] photo = item10.getImagen();
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
oImage = response.getOutputStream();
oImage.write(photo);
oImage.flush();
oImage.close();
} catch (Exception e) {
e.printStackTrace();
}
}
With this code, i show a full screen, and i need inject in jsp. Any idea?
Thanks
You need to return Base64 encoded image bytes in String to your JSP page and use:
<img src="data:image/png;base64,${yourBase64EncodedBytesString}"/>
to display your image.
Use Apache Commons Codec to do Base64 encodings.
So for e.g.:
String yourBase64EncodedBytesString = new String(Base64.encodeBase64(content));
Set it for e.g. as a request attribute:
request.setAttribute("yourBase64EncodedBytesString", yourBase64EncodedBytesString);
And retrieve in JSP page:
<img src="data:image/png;base64,${requestScope['yourBase64EncodedBytesString']}"/>
I am submitting a form using jquery in my Spring mvc.
this is the jquery call to submit form.
function uploadJqueryFormForEdit(documentId){
alert("ccc");
$('#result').html('');
$("#editDocumentForm").ajaxForm({
success:function(data) {
alert("ddd");
$('#result').html(data);
alert("eee");
//getProjectSegment('documents','DocumentSegment',projectId);
$('#editDocumentForm').remove();
},
error:function(e){
alert(e.responseText);
$("#msgDiv").html('Error');
},
dataType:"text"
}).submit();
}
And this is the form that I'm going to submit.
<form action="cont/uploadEdit?documentId=15&projectId=2" name="editDocumentForm" id="editDocumentForm" enctype="multipart/form-data" method="post">
When i'm using one parameter in action url, eg.
action="cont/uploadEdit?documentId=15"
it works fine. but when i'm using two parameters as
action="cont/uploadEdit?documentId=15&projectId=2"
it doesn't call to controller method correctly(not hitting that method at all)
here is the controller method
#RequestMapping(value = "cont/uploadEdit", method = RequestMethod.POST)
public #ResponseBody String uploadEdit(#ModelAttribute("sessionId") String sessionId,#RequestParam("documentId") int documentId,#RequestParam("projectId") int projectId,MultipartHttpServletRequest request, HttpServletResponse response, UploadedFile fileDetail,UserBean userbean,Model model) throws SessionException {
logger.info("uploadEdit");
}
why can't I use two parameters in action tag.?
this is the controller method that worked fine with first action
#RequestMapping(value = "cont/uploadEdit", method = RequestMethod.POST)
public #ResponseBody String uploadEdit(#ModelAttribute("sessionId") String sessionId,#RequestParam("documentId") int documentId,MultipartHttpServletRequest request, HttpServletResponse response, UploadedFile fileDetail,UserBean userbean,Model model) throws SessionException {
logger.info("uploadEdit");
}
Add params = {"documentId", "projectId"} attribute to the RequestMapping annotation
#RequestMapping(value = "cont/uploadEdit", params = {"documentId", "projectId"}, method = RequestMethod.POST)
public #ResponseBody String uploadEdit(#ModelAttribute("sessionId") String sessionId,#RequestParam("documentId") int documentId,#RequestParam("projectId") int projectId,MultipartHttpServletRequest request, HttpServletResponse response, UploadedFile fileDetail,UserBean userbean,Model model) throws SessionException {
logger.info("uploadEdit");
found the error:
In the form that we are going to submit (in my case "editDocumentForm") there should be no any other input tags with the same name as in action url variables,
eg if there is something like this,
<input type="hidden" id="projectId" name="projectId" value="somevalue"/>
it will make conflicts. So make sure that no conflicts occur.
I have a stream of bytes for a pdf file which I have stored in a session.
#RequestMapping(value = "/start.htm")
public String start(HttpServletRequest request, Model model)
throws Exception
{
// do something
request.getSession().setAttribute(uniqueId,bytesOfaPDF);
return "jspname";
}
Now I have put this in my JSP.
<object id="COB" data="/retrievePdf.htm" type="application/pdf" width="100%" height="100%">
</object>
Now I have to write another method in my controller with the same mapping (retrievePdf) which will show PDF.
#RequestMapping(value="/retrievePdf.htm", method=RequestMethod.GET)
public void retrievePdf(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)throws OSOSystemException
{
byte[] db = (byte[]) request.getSession().getAttribute(uniqueId);
response.getOutputStream().write(db);
response.setContentType("application/pdf");
response.setContentLength(db.length);
}
But I am not able to understand how I can pass uniqueId to retrievePdf?
How I can achieve this?
Thanks in advance.
Pass the unique ID as a query string in the URL
Store the unique id in request
#RequestMapping(value = "/start.htm")
public String start(HttpServletRequest request, Model model)
throws Exception
{
// do something
// storing uniqueId
request.getSession().setAttribute("uniqueId",uniqueId) ;
request.getSession().setAttribute(uniqueId,bytesOfaPDF);
return "jspname";
}
In Jsp append the URL dynamicaally:
<% String uniqueId=request.getSession().getAttribute("uniqueId") ;
String url = "/retrievePdf.htm?uniqueId="+uniqueId ;
%>
<object id="COB" data="<%=url%>" type="application/pdf" width="100%" height="100%">
</object>
Add requestParam for uniqueId in the below method and process it
#RequestMapping(value="/retrievePdf.htm", method=RequestMethod.GET)
public void retrievePdf(HttpServletRequest request, HttpServletResponse response, #RequestParam(value="uniqueId",required=true)String uniqueId,ModelMap modelMap)throws OSOSystemException
{
byte[] db = (byte[]) request.getSession().getAttribute(uniqueId);
response.getOutputStream().write(db);
response.setContentType("application/pdf");
response.setContentLength(db.length);
}
Thats all, it will work !!