I want to display image on the page that is returned by the java controller.
Java controller:
public FileSystemResource RetrieveLogo(#PathVariable("UniqueCode") String Code){
// get image file
return fileSystemResource;
}
at java script controller, I make a service call to get the image .
Javascript controller:
$scope.logo = function() {
rest.retrieveLogoForMerchant({id: 'abcd'}).$promise.then(function(data) {
console.log("-------------success--------- " + angular.toJson(data));
$scope.logoImage = angular.toJson(data);
});
}
Here the console prints -
{"0":"�","1":"�","2":"�","3":"�","4":"\u00.......etc}
On Html page
<img ng-src="{{logoImage}}" height="100" width="100"/>
On the page image displays blank and gives error in the console that -
http://localhost:9090/%7B%220%22:%22%EF%BF%BD%22,%221%22:%22%EF%BF%BD%22,%2…22%EF%BF%BD%22,%22246%22:%22\u0007%22,%22247%22:%22\u0014%22,%22248%22:%22 400 (Bad Request)
Suggest me ,that how can I display image properly.
Thanks
Try removing the the angular.toJSON method here:
$scope.logoImage = angular.toJson(data);
And also
I think you are loading image through binary data append proper image encoding
to the data Eg: ng-source={{data:image/png;base64........}}
You need to set the right content type in response inside your Java controller, see below function
public void displayImage(HttpServletResponse response, byte[] imageArray) throws ServletException, IOException {
System.out.println("Inside display Image function");
if (imageArray != null && imageArray.length > 0) {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
System.out.println("Image Array is not null :" + imageArray);
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
out.write(imageArray);
out.flush();
out.close();
} else {
System.out.println("Image is null");
}
}
Than you need to make sure append that appropriate header before data content while setting it to img tag.. #Naveen has already pointed about it in his answer. Basically you need to have something like this
<img src="data:image/png;base64,/*Your data part goes here*//>
You also need to encode the stream to Base64 before assigning it to img. I had below line in my jsp you can alter it to suit your need..
<img id="userProfileImg" height="150px" width="150px" name="userProfileImg" alt="../img/user_default_pic.png" src='data:image/jpg;base64,<%=Base64.encode(/*Blob data returned from database*/)%>'/>
Why don't you get the URL of the image via http (ajax call) and on success $scope.logoImage = data. data is the URL of the image retrieved via http.
Related
I want to allow the user to download a pdf file created in iText.
The expected result is that the user can download the pdf to their selected directory. The actual result is the file will not download.
I am generating a pdf using iText and passing the result back to my ajax call to allow the user to download the file. I have the base64. I checked that it was valid by using https://base64.guru/converter/decode/pdf This showed the pdf correctly. However, I can not get the result to download in the ajax ".done".
I have tried using:
byte[] decoder = Base64.getDecoder().decode(b64);
Before passing it back; however, I get an error message on ".getDecoder()" of "The method getDecoder() is undefined for the type Base64".
The java code is:
resourceImage = MySQLConnection.recipePDF(accountID, crID, servings, servingSize);
String imageDataString = Base64Encode2.encode(resourceImage);
System.out.println("imageDataString: " + imageDataString);
if (resourceImage == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No recipe pdf.");
} else {
String json = new Gson().toJson(imageDataString);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
The javascript/ajax code on the is:
.done(function(responseJson1a){
dataType: "json";
alert(JSON.stringify(responseJson1a));
download(responseJson1a, "resourcefile.pdf", "application/pdf");
});
A very simple answer. I needed to add "data:application/pdf;base64," to the start of the string.
download("data:application/pdf;base64,"+responseJson1a, "resourcefile.pdf", "application/pdf");
I have a jsp that makes an AJAX call to a helper jsp which calls a java bean that creates an image. The helper JSP then loads the image into a byte array encodes it to Base64 using Apache commons and returns the string.
File imageFile = new File("test.png");
response.setHeader("Content-Type", getServletContext().getMimeType(imageFile.getAbsolutePath()));
response.setHeader("Content-Length", String.valueOf(imageFile.length()));
FileInputStream is = new FileInputStream(imageFile);
byte[] buffer = new byte[(int)imageFile.length()]; // 32k buffer
int offset = 0;
while ( offset < buffer.length ) {
int count = is.read(buffer, offset, buffer.length - offset);
offset += count;
}
byte[] encoded = Base64.encodeBase64(buffer);
String encodedFile = Base64.encodeBase64String(encoded);
out.print(encodedFile);
out.flush();
Here is the javascript that makes and receives the request for the image:
function getContourImage(startDate, stopDate){
$.ajax("services/contour.jsp", {
data: {
startDate: startDate,
stopDate: stopDate
},
dataType: "json",
traditional: true,
success: contourImageHandler()
});
}
function contourImageHandler(resp){
alert("resp: " + resp);
$( "#plot" ).attr("src","data:image/png;base64," + resp);
}
This is the image display area in the html:
<div id="imageDisplay" name="imageDisplayDiv"
img name="contourImageLocation"
id="plot" src="images/test.png" width="1200" height="1200">
I can see the response in the firebug panel and it seems to have data. The alert statement in the ajax response handler says the response is undefined and no image is placed in the plot location. Does anyone know what I have done wrong?
For the 'displaying the image' part of your problem you can go through this:
http://danielmclaren.com/node/90
Also, it would be better if 'helper jsp' work is moved to a Servlet as you may get additional/junk spaces and line breaks in a jsp response.
I am trying to retrieve images from database.
Currently i was able to show :
`com.mysql.jdbc.Blob#2aba2aba `
in my jsp output.
May i know how to convert that into an image?
i have use the below to call out the above
photo[i].getPhotoFileData();
This is more of an issue with the way HTML documents work than with your JSP. You need to understand that HTML doesn't embed images directly. Instead, it uses <img> tags to reference images hosted at different URLs.
In order to display an image stored in a database on an HTML page you're going to need a separate servlet that can handle requests for the image. Your JSP should render an HTML document like the following:
<html>
<head>
...
</head>
<body>
...
<img src="www.mydomain.com/images/1234.png" />
...
</body>
</html>
Then you would create a separate servlet to handle all the requests to /images which would make a database call and send the raw bytes from the blob it gets back to the response's output stream. Make sure you also set the Content-Type header correctly based on what image encoding you're using.
In order to send the image back to the requester you have one of two options. You can get the blob's bytes as an array and write that to the OutputStream (e.g. out.write(blob.getBytes(0,blob.length());). Or you can use the getBinaryStream() method and then copy bytes from the InputStream to the OutputStream. Here's an example of that:
public static void copy(Blob from, OutputStream to)
throws IOException {
byte[] buf = new byte[4096];
try(InputStream is = from.getBinaryStream()) {
while (true) {
int r = is.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
}
}
}
NB: This code has not been tested or even compiled, it should only be used as a starting point.
You're getting a Blob object - not it's contents. If you want to get raw byte data you have to ask the Blob object for it, e.g.:
Blob blob = photo[i].getPhotoFileData();
byte[] data = blob.getBytes(0, blob.length());
If you want to create an image on the fly, then just call:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
You can then save the image or ... actually I don't know what else. Thing. Stuff. Display it. Print. Limitless possibilities! Just like at zombo.com!
first convert blob to input stream to string . then use that String instead of image URL .
Converting blob to String
try {
Blob blob = staticOffer.getImage(); //blob of image from db
strOut = new StringBuffer();
String aux;
BufferedReader br;
br = new BufferedReader(new InputStreamReader(blob.getBinaryStream()));
while ((aux=br.readLine())!=null) {
strOut.append(aux);
}
offerPicStr = strOut.toString();
} catch (Exception e) {
e.printStackTrace();
}
Now use that string it html/jsp in following way
<img src="data:image/jpeg;base64,${offerPicStr}" width="100" height="100"></img>
With this code i am able to render a image from a servlet ,But my business says.I need to add a link say"www.google.com".If i click this image.Is there any way that i can access a image with the link on.I need to flush it directly from the servlet should not use jsp.Can any one please help me out.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletContext sc = getServletContext();
String filename = sc.getRealPath("image.JPG");
resp.setContentType("image/jpeg");
// Set content size
File file = new File(filename);
resp.setContentLength((int)file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request , response);
// TODO Auto-generated method stub
}
}
You need to put an <a> element around the <img> element in the markup.
<a href="http://www.google.com">
<img src="imageServlet" />
</a>
By the way, the sc.getRealPath() suggests that your image file is already in public webcontent folder. Why not just using <img src="image.JPG"> instead? Or is the servlet heavily oversimplified?
In short you want to add a link say google.com and on click of it shows a image.
Firstly you don't need to send image as a response rather you need to anchor link and add javascript function onclick on that link.
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" +
"<HTML>\n" +
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<a href='www.google.com'><img src='imagePath' /></a>\n" +
"</BODY></HTML>");
If I undestood correct you can return html with link on image:
<img src="yourImageRenderingServletPath">
So you will have one servlet that render html and second that render image. To prevent image buffering in browser you can add random param id = (new Random()).nextInt():
<img src="yourImageRenderingServletPath?id=124">
This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 3 years ago.
My ImageDAO looks like this:
public InputStream getPhotos(Long userid) throws
IllegalArgumentException, SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
Database database = new Database();
InputStream binaryStream = null;
try {
connection = database.openConnection();
preparedStatement = connection.prepareStatement(SQL_GET_PHOTO);
preparedStatement.setLong(1, userid);
preparedStatement.executeUpdate();
while(resultset.next()) {
binaryStream = resultset.getBinaryStream(4);
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
close(connection, preparedStatement, resultset);
}
return binaryStream;
}
My ImageServlet looks like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Getting user id from session
HttpSession session = request.getSession(false);
Long userid = (Long) session.getAttribute("user");
try {
InputStream photoStream = imageDAO.getPhotos(userid);
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams
input = new BufferedInputStream(photoStream, 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 {
output.close();
input.close();
}
//Redirect it to profile page
RequestDispatcher rd = request.getRequestDispatcher
("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
How should my JSP image src look like
<img src="What to put here">
Disclosure:
The servlet code is copied from this link http://balusc.blogspot.com/2007/04/imageservlet.html
Questions:
How to retreive image in JSP from ImageServlet. Someone in Stackoverflow said to put
<img src="URL to Servlet" />. But I don't what it means.
Is the above method correct way to retreive image from database? Or is there better way.
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>
The src of the HTML <img> element should just point to an URL. An URL is a web address like as the one you enter in your browser address bar. Servlets can be mapped on certain URL patterns by web.xml so that when you invoke an URL which matches the servlet mapping, that the servlet will be invoked. See also our Servlets Wiki.
You have mapped the servlet on an URL pattern of /Photos. Entering an URL like
http://localhost:8080/YourContextPath/Photos
in the browser address bar should display the image. So basically, assuming that the JSP runs in the same context path, this should do:
<img src="Photos" />
Or when you want to make it relative to the domain root, then you need to include the context path dynamically:
<img src="${pageContext.request.contextPath}/Photos" />
Said that, there are some problems in your servlet. You haven't set the content type header. This way the browser won't know what to do with the HTTP response. It'll display a Save As popup when you enter its URL straight in address bar and it'll display nothing when you call it in <img>. If it's a JPG image, then add the following line before you call response.getOutputStream().
response.setContentType("image/jpeg");
This way the browser understands that it's a JPG image and it'll display it as such. See also the blog which you linked for the proper way of setting the headers.
Another problem is that you're calling request.getSession(false) which can potentially return null when there's no means of a session. But you are not checking for that on the next line! So either use
HttpSession session = request.getSession();
so that it is never null, or add a
if (session == null) {
// Display some default image or return a 404 instead.
return;
}
You would like to do the same for userId and photoStream. If it's absent, then display a default image or return a 404.
Attach your web.xml to see how you are (if you are at all) mapping your servlet, so we can give you the URL.
web.xml is the way to tie URLs with the servlets.
Your way with buffered output towards Servlet output stream is IMHO a correct and good way of writing data to output. It would be better to use Filter to cache output though instead of writing the response all the time.
UPDATE:
Based on the blog you mentioned as source and web.xml in it, the correct url should be
<img src="/image/my_image.jpg" />
where my_image.jpg is a sample name of uploaded image.
If you register your serlvet for the pattern /Photos
<img src="/yourContextRoot/Photos" />