Image not being displayed in browser - java

I am having an image stored at a location say : C:\Users\admin\Desktop\SharedCrpto1\web\RetrievedFiles\FILE310#ST-testemp\abc.png .Now when i try to show it in my jsp page the image is not getting visible even when the path to image is correct.
This image is to be displayed after my server process the browsed image provided by the client.
I tried :
<img src="<%=path%>" alt="No image" />
The image in the particular folder is being created by my servlet like this :
File filesstore = new File("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\RetrievedFiles\\FILE310#ST-testemp\\");
if(!filesstore.exists())
{
System.out.println("MAKING DIRECTORY..");
filesstore.mkdirs();
}
To copy one file to this location I did :
FileInputStream fis = new FileInputStream("C:\\test.png");
int xx=fis.available();
byte[] b = new byte[xx];
fis.read(b);
FileOutputStream fos=new FileOutputStream("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\RetrievedFiles\\FILE310#ST-testemp\\abc.png");
fos.write(b);
Am i doing something wrong?Please help

From your question what I understood is that You want to read a image file from your local file system & display in a jsp page using
STEP 1
For this you need a servlet or jsp which will read the file and convert to byte[] and again write the byte[] to ServletOutputStream .
STEP 2:
Create a JSP page which have a img tag & it's src should point to servlet url instead of real file path.As img tag's src attribute can take file path or byte stream.In this we are giving it byte stream because file path will not work.
When you call your jsp page it will try to render the img tag and at that time it will call your servlet & get the byte stream of image data .So it will render your image
Image Servlet
#WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//place your file path
File imageFile =new File("/home/ashok/Pictures/Siberischer.jpg");
ServletOutputStream outputStream = response.getOutputStream();
byte[] imageBytes = FileUtils.readFileToByteArray(imageFile);
outputStream.write(imageBytes);
outputStream.close();
}
}
JSP PAGE(to display image) In your jsp just write this tag
JspPage is the application name & ImageServlet is the servlet url pattern
<img alt="NO IMAGE" src="/JspImage/ImageServlet">
FileUtils is present Apache Commons IO Library download the jar to your project

Related

Load image Dynamically via Java servlet

I am trying to load images from server to my JSP
My files are:
image.jsp
<img src='servlet1' height='300px'/>
DisplayImage.java
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("path/to/my/img.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0;
while((ch=bin.read())!=-1){
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}
}
Application I'm supposed to build is a Vehicle Directory where I can upload images, and these images are stored in a folder /home/upload/ outside CATALINA
(NB: I didn't use a folder inside project directory coz I am deploying the project via *.war file, which removes every files inside when a new version needs to be deployed.)
I want to display the details and image based on search parameters.
( Edit: I have the file name stored in database when I upload them, so can get the list of image names from DB for a particular vehicle, Since it is stored in folder /home/upload/ , full path will be like /home/upload/fileName.jpg which I need to pass to servlet to load)
Problem I face is that:
image src attribute is specified as servlet1 and the servlet by default serves the image from path defined in DisplayImage.java file
Is there any way that I can pass /another/file/Path.jpg or fileName.jpg to the servlet so that I can display other image files too,
Yeah, In JSP, you can pass your search parameters in request.
Like
<input id="imageSerach" name="imageSerach"/>
<div id="ImageContent"/>
and make ajax call to servlet with imageSearch param.
$.ajax({
url: servleturl,
data: {
imageSerach : $('#imageSerach').val()
},
success: function(responseData){
$('#ImageContent').html('<img src="data:image/png;base64,' + responseData + '" />');
}
});
Servlet :-
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
String fileName = req.getParameter("imageSerach");
response.setContentType("image/jpeg");
ServletOutputStream out;
File f = new File("path/of/file/"+fileName);
if (f.exists())
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("path/of/file/"+fileName);
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0;
while((ch=bin.read())!=-1){
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
else
// no file exit
}
}

download excel generated file

I have this button on my html page.
When I click it, exportCOAExcel gets triggered.
Then a excel workbook is generated and save to a path.
I want a prompt to come to say which path you want to download the file to? or save to the deafult 'download' folder location of the browser.
#GetMapping(value = "/coaExport", params = "action=excel")
public void exportCOAExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
//loogic to fill up the excel workbook with data
FileOutputStream outputStream = new
FileOutputStream("C:\\Users\\user\\Desktop\\revenue.xls");
workbook.write(outputStream);
outputStream.close();
}
You need to send a content disposition response to the browser, so that it can understand that it is a file to download.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

How to send an image over Java HTTP server

I'm developing an HTTP server using HttpServer and HttpHandler.
The server should response to clients with XML data or images.
So far, I have developed HttpHandler implementations which respond to the clients with the XML data but I couldn't implement a HttpHandler which reads the image from file and send it to the client (e.g., a browser).
The image should not be loaded fully into memory so I need some kind of streaming solution.
public class ImagesHandler implements HttpHandler {
#Override
public void handle(HttpExchange arg0) throws IOException {
File file=new File("/root/images/test.gif");
BufferedImage bufferedImage=ImageIO.read(file);
WritableRaster writableRaster=bufferedImage.getRaster();
DataBufferByte data=(DataBufferByte) writableRaster.getDataBuffer();
arg0.sendResponseHeaders(200, data.getData().length);
OutputStream outputStream=arg0.getResponseBody();
outputStream.write(data.getData());
outputStream.close();
}
}
This code just sends 512 bytes of data to the browser.
You're doing way too much work here: decoding the image, and storing it in memory. You shouldn't try to read the file as an image. That is useless. All the browser needs is the bytes that are in the image file. So you should simply send the bytes in the image file as is:
File file = new File("/root/images/test.gif");
arg0.sendResponseHeaders(200, file.length());
// TODO set the Content-Type header to image/gif
OutputStream outputStream=arg0.getResponseBody();
Files.copy(file.toPath(), outputStream);
outputStream.close();
DataBufferByte stores its data in banks. getData() retrieves only the first bank, so you're declaring a length of only the first bank and then writing only the first bank.
Instead of your current write line, try this instead (untested):
arg0.sendResponseHeaders(200, data.getDataTypeSize(TYPE_BYTE));
OutputStream outputStream=arg0.getResponseBody();
for (byte[] dataBank : data.getBankData()) {
outputStream.write(dataBank);
}
outputStream.close

Rendering generated png into JSF

I built an image form PDF doc inside a JSF backing bean, i need to show image inside JSF page. I found that primefaces has a component named , I defined a variable:
private StreamedContent pdfImage;
according to this example http://www.primefaces.org/showcase/ui/dynamicImage.jsf. In my code
i built pdf using some data and apache PDFBox and save document into:
private byte[] bytesPdf;
My jsf line is
<p:graphicImage value="#{myBean.pdfImage}" rendered="#{myBean.showImage}"/>
After that i call following method that tranform first PDF document page to PNG i get:
public void buildPDFImage() throws IOException{
ByteArrayOutputStream os = new ByteArrayOutputStream();
//Build bufferedImage from pdf bytearray
InputStream input = new ByteArrayInputStream(bytesPdf);
PDDocument archivo=new PDDocument();
archivo=PDDocument.load(input);
PDPage firstPage = (PDPage) archivo.getDocumentCatalog().getAllPages().get(0);
BufferedImage bufferedImage = firstPage.convertToImage();
//File exit=new File("d:/exit.png"); if i do something like this and pass file as param to iowrite image is generated on file system
try {
ImageIO.write(bufferedImage, "png", os);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pdfImage = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");
}
When i run my app after generate pdf image i get this trace
GRAVE: Error Rendering View[/pages/apphuella.xhtml]
java.lang.IllegalStateException: PWC3999: Cannot create a session after the response has been committed
at org.apache.catalina.connector.Request.doGetSession(Request.java:2880)
at org.apache.catalina.connector.Request.getSession(Request.java:2577)
at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:920)
at com.sun.faces.context.SessionMap.getSession(SessionMap.java:235)
at com.sun.faces.context.SessionMap.put(SessionMap.java:126)
at com.sun.faces.context.SessionMap.put(SessionMap.java:61)
at org.primefaces.component.graphicimage.GraphicImageRenderer.getImageSrc(GraphicImageRenderer.java:105)
at org.primefaces.component.graphicimage.GraphicImageRenderer.encodeEnd(GraphicImageRenderer.java:45)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at
I would know if i´m using correctly if don´t how could i use it to show generated png(and other images)?, also if there´s other option to show runtime generated images on JSF pages.
Thanks in advance
At first, you need to keep the file a temporary directory. After that you should render the file again.
Try as below
Backing Bean
private String filePath;
public String filePath() {
return filePath;
}
private String getSystemPath() {
Object context = getFacesContext().getExternalContext().getContext();
String systemPath = ((ServletContext)context).getRealPath("/");
return systemPath;
}
public void buildPDFImage() throws IOException {
// create any kind of file types.
byte[] cotent = --> take byte array content of your files.
Stirng fileName = "xxx.pdf" or "xxx.png" --> your file name
String dirPath = "/pdf/" or "/images/"; --> a directory to place created files.
filePath = dirPath + fileName
createFile(new File(getSystemPath() + filePath), content);
}
private void createFile(File file, byte[] content) {
try {
/*At First : Create directory of target file*/
String filePath = file.getPath();
int lastIndex = filePath.lastIndexOf("\\") + 1;
FileUtils.forceMkdir(new File(filePath.substring(0, lastIndex)));
/*Create target file*/
FileOutputStream outputStream = new FileOutputStream(file);
IOUtils.write(content, outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Pages
<h:form enctype="multipart/form-data">
<h:commandButton value="Create"/>
<!-- Your Files is image -->
<p:graphicImage value="#{myBean.filePath}"/>
<!--
Your Files is pdf. You need PDF Viewer plugin for your browser.
My FireFox vesion is 20.0. It have default PDF Viewer.
If PDF File cannot display on your browser, it is depond on browser setting also.
-->
<p:media value="#{myBean.filePath}" width="100%" height="300px"/>
</h:form>

file upload with spring MVC

I am uploading file using spring MVC and jquery. Inside my class method I have written
#RequestMapping(value="attachFile", method=RequestMethod.POST)
public #ResponseBody List<FileAttachment> upload(
#RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpSession session) {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
//Save the file to a temporary location
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
fileName = realContextPath +"/images/"+file.getOriginalFilename();
//File dest = new File(fileName);
try {
//file.transferTo(dest);
inputStream = file.getInputStream();
outputStream = new FileOutputStream(fileName);
inputStream.close();
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Its uploading the file correctly I am using
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
to get the path. My first question is , Is this the correct way to get the path and it stores the file somewhere at
workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images
and when I am trying to display this image on my jsp page using the following code
<img src="<%=request.getRealPath("/") + "images/images.jpg" %>" alt="Upload Image" />
It does not display the image, Its generating the following html
<img src="/home/name/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images/images.jpg" alt="Upload Image">
Am I doing the things right? In my project I have to upload large number of files everyday.
Please let me know if you need anything else to understand my question
It will be better if you upload your files in some directory by absolute path(e.g. C:\images\) instead of relative (your approach). Usually, web apps runs on linux mathines on production and it is good practice to make save path configurable.
Create some application property which will holds save path for files(in xml or property file).

Categories