display image in JSP using Spring - java

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']}"/>

Related

Spring doesnt display images when there is a path variable on URI

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.

How to add download pdf link in button in preview page using thymleaf html in java?

How to add a download link in HTML preview page using thymleaf java? I have added controller code for download and also html code which i tried. I need to refer download endpoint from the controller, So I have attached the code for download pdf. Download pdf has two scenarios as mentioned below(api/v1/download?s and api/v1/download?s=1). How do I interpret and refer this endpoint to create the download button based on user inpt(EX:api/v1/download?s=1), it needs to redirect to api/v1/download?s=1 and download the pdf via thymleaf html.
Download URL:
api/v1/download?s
api/v1/download?s=1
// html code
</div>
<a th:href="#{|/download|}">download</a>
<span>Download</span>
</a>
</div>
// download code
#GetMapping("/{id}/download")
public void download(#PathVariable(BaseEntity.ID) String id, #RequestParam(name = "s") String sensitive,
HttpServletResponse response) {
try {
Path file = Paths.get(profilePdfService.generatePdf(id, sensitive).getAbsolutePath());
if (Files.exists(file)) {
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + file.getFileName());
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}

upload and view image in spring mvc

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.

Return a PDF file with Spring MVC

Actually, I have that functionality, I got a frame where I set the URL (ip:port/birt/preview?__report=report.rptdesign&__format=pdf&parameters...) and that frame renders the PDF file.
But I want that URL hidden...
I need return a PDF file with Spring MVC but that PDF is generated by another application.
This means I got another app (Eclipse Birt Engine) that I pass the parameters through of an URL (ip:port/birt/preview?__report=report.rptdesign&__format=pdf&parameters...) and it generates a PDF file, I need from my controller get that PDF and return it with Spring MVC. Could somebody help?
That would be like the below:
#Controller
#RequestMapping("/generateReport.do")
public class ReportController
#RequestMapping(method = RequestMethod.POST)
public void generateReport(HttpServletResponse response) throws Exception {
byte[] data = //read PDF as byte stream
streamReport(response, data, "my_report.pdf"));
}
protected void streamReport(HttpServletResponse response, byte[] data, String name)
throws IOException {
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=" + name);
response.setContentLength(data.length);
response.getOutputStream().write(data);
response.getOutputStream().flush();
}
}
PDF content is just bytes so you can just write the PDF content bytes to the HttpResponse output stream.

How to show a JSP page using Servlet which has image in its Response?

Servlet doGet() code for getting an Image from Database and to store image in Response
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get userid from session
try {
// Get photos from database in (image)
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(image.getContenttype());
response.setHeader("Content-Length", String.valueOf(image.getLength()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getTitle()
+ "\"");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(image.getPhoto(), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
// Gently close streams.
output.close();
input.close();
}
//Redirect it to photo page
RequestDispatcher rd = request.getRequestDispatcher
("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
However, When this servlet shows the JSP page it shows only image and not the JSP page.
JSP code:
... JSP code
<img src="Servlet url">
... JSP code cont...
What output I get:
I only get Image instead of image inside JSP
When I use RequestDispatcher/sendRedirect() I get following Exception java.lang.IllegalStateException: Cannot forward after response has been committed
Question:
How to get Image inside JSP instead of just Image in browser
How to avoid above Exception?
EDIT: My Web.xml looks like this
<servlet>
<servlet-name>Photo Module</servlet-name>
<servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Photo Module</servlet-name>
<url-pattern>/Photos</url-pattern>
</servlet-mapping>
How to get Image inside JSP instead of just Image in browser
Enter the URL to the JSP file containing the <img> element in the browser address bar.
http://localhost:8080/contextname/webplugin/jsp/profile/photos.jsp
How to avoid above Exception?
Remove the following lines from the servlet code.
//Redirect it to profile page
RequestDispatcher rd = request.getRequestDispatcher
("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
The servlet should just return the image. Nothing more. It's the webbrowser itself who is supposed to download and display the image, not the webserver.
See also:
How to retrieve image from database and display in JSP via Servlet?
How to retrieve and display images from a database in a JSP page?
1 you are modifying response and then forwarding , it is useless. don't do it.
2 How to get image from servlet to jsp

Categories

Resources