This question is continuation to my previous question Accessing External Files Into Our Web Application, actually I am uploading file using Struts tag <html:file property="file" />
But now I wanted to show the uploaded images from that location but I am getting src
location as http://localhost:9443/D:/resources/images/img1.jpg
which is not a valid path for that image.
How to access that image which is outside my server directory.
This is how I am sending Ajax response with Absolute path of images
public ActionForward getAjaxUploadedFiles(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
{
String imagePath = "D:/resources/images/";
ArrayList<String> path = new ArrayList<String>();
File imageFile = new File(imagePath);
File imageFiles[] = imageFile.listFiles();
for (int i = 0; i < imageFiles.length; i++) {
path.add(imageFiles[i].getAbsolutePath());
}
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.setStatus(HttpServletResponse.SC_OK);
StringBuffer strXMl = new StringBuffer();
strXMl.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
strXMl.append("<start>");
for (String imagePth : path) {
strXMl.append("<imagePath>");
strXMl.append(imagePth);
strXMl.append("</imagePath>");
}
strXMl.append("</start>");
if(strXMl != null){
String Xml = strXMl.toString();
out.write(Xml);
System.err.println("XMl Reponse is: " + Xml);
}
else {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
out.flush();
return mapping.findForward(null);
}
This is how I am rendering images at JSP
$(response).find("imagePath").each(function() {
row = tblReportList.insertRow(0);
row.className="TableBordergray";
row.style.width="100%";
var imagePath = $(this).text();
cell = row.insertCell(0);
cell.innerHTML="<img src='" + imagePath + "' alt='" + imagePath + "' height='42' width='42'>";
});
but at <img>
tag I am getting image path as http://localhost:9443/D:/resources/images/img1.jpg
You can't render images in such way. Web server treated your image path as relative and add qualifying url location on the server. You should create an action to serve images, for example
<action path="/image" ... scope="request" validate="false"/>
Then render HTML like
cell.innerHTML="<img src='" + '/image?path=' + imagePath + "' alt='" + imagePath + "' height='42' width='42'>";
Now, create the action that write the binary image data to the response output stream. Take a parameter path
in the action that let you find a file for binary output. After the flushing output return null
so struts should not forward the action further. You could also add headers to turn off a Cache-Control
to make sure the images are retrieved from the server.