Jsp loading image from webapps ROOT folder - java

I am working on a Java application and what I want to do is to give to the users the functionality to upload an image and view it at their profile. I know similar questions have been answered many many times but this is my first time doing this and I am really struggling to make it work.
So this is my testing code:
upload.jsp
...
<body>
<form method="post" action="FileUploader" encType="multipart/form-data">
<input type="file" name="file" value="select images..."/>
<input type="submit" value="start upload"/>
</form>
</body>
...
FileUploader.java
As you can see here, I store all my images in Tomcat's webapps/ROOT/files folder.
#WebServlet("/FileUploader")
public class FileUploader extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
if(!ServletFileUpload.isMultipartContent(request)){
out.println("Nothing to upload");
return;
}
FileItemFactory itemfactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(itemfactory);
try{
List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
for(FileItem item:items){
String contentType = item.getContentType();
if(!contentType.equals("image/png")){
out.println("only png format image files supported");
continue;
}
File uploadDir = new File("/home/agg/apache-tomcat/webapps/ROOT/files");
File file = File.createTempFile("img",".png",uploadDir);
item.write(file);
out.println("Filename: " + file.getName());
out.println("File Saved Successfully");
response.sendRedirect("message.jsp");
}
}
catch(FileUploadException e){
out.println("upload fail");
}
catch(Exception ex){
out.println("can't save");
}
}
}
message.jsp
Here, I am trying to load one of the images saved through another servlet.
...
<body>
<img src="file/img1.png">
</body>
FileServlet.java
Servlet that retrieves the image.
#WebServlet("/file/*")
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private String filePath;
public void init() throws ServletException {
this.filePath = "/files";
}
protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("================In do get==================");
// Get requested file by path info.
String requestedFile = request.getPathInfo();
System.out.println("Requested File: " + requestedFile);
// Check if file is actually supplied to the request URI.
if (requestedFile == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Decode the file name (might contain spaces and on) and prepare file object.
File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
System.out.println("Filename: " + file.getName());
System.out.println(file.getAbsolutePath());
// Check if file actually exists in filesystem.
if (!file.exists()) {
System.out.println("DOES NOT EXIST");
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// more code here but it does not matter
}
}
The problem is that the image does not load. The path printed at the console seems to be correct. What am I missing here?

For me your problem is here
<img src="file/img1.png">
It doesn't seem to be the correct path for the next reasons:
The root directory is /.../webapps/ROOT/files so it should start with files not file.
The name of the file should be img + a random long + .png here you set the random long to 1 which doesn't seem to be correct
As it is in the ROOT webapp, you should rather put an absolute path instead of a relative path, in other words the path should start with a slash

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
}
}

JSF application: Open file, not download it

Current situation: I'm trying to create a JSF app (portlet) which should contains links to excel files (xls, xlt) stored on public network drive G: mapped for all users in our company. The main goal is to unify access to these files and save work to users in search of the reports somewhere on G drive. I hope it's clear..?
I'm using following servlet to open a file. Problem is, that it's not just opened, but downloaded by browser and after that, opened:
#WebServlet(name="fileHandler", urlPatterns={"/fileHandler/*"})
public class FileServlet extends HttpServlet
{
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private String filePath;
public void init() throws ServletException {
this.filePath = "c:\\Export";
System.out.println("fileServlet initialized: " + this.filePath);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
String requestedFile = request.getPathInfo();
File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
String contentType = getServletContext().getMimeType(file.getName());
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
close(output);
close(input);
}
}
private static void close(Closeable resource) {
if (resource != null) resource.close();
}
}
How to just start appropriate application (e.g. Excel, Word, etc.) clicking on link (with absolute file path) and open the file in its original location?
UPDATE: I'm trying to use <a> tag:
File // various "/" "\" "\\" combinations
File
But it doesn't work:
type Status report
message /G:/file.xls
description The requested resource is not available.
File URLs are considered as a security risk by most browsers, because they cause files to be opened on a client's machine by a web page, without the end user being aware of it. If you really want to do that, you'll have to configure the browser to allow it.
See the wikipedia article for solutions.

Uploading a file in Java Servlet

I have a Java Dynamic Web Project, and I'm using TomCat v7.0.
I am new to web projects and I didn't quite understand how I can upload a file in one of my jsp pages. Since my project is intended to be only local, I thought I could use a multipart form in which the person would choose the file (and this part goes fine) and later retreive the file path from my Servlet. I can't complete this part though, it appears to only give me the name of the file, not its entire path.
Can anyone point me to the right direction? I've read several posts about Apache File Upload and retreiving information from the multipart form but nothing seems to help me.
How can I get the file path from a form or alternatively how can I get the uploaded file to use in my Java classes?
Thanks in advance.
.jsp:
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="filePath" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"></input>
<input type="submit" value="Enviar"></input>
</form>
Java Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<html><body>");
try
{
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items)
{
if (item.isFormField())
{
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
out.println("<h1>"+fieldname+" / "+fieldvalue+"</h1>");
}
else
{
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = item.getName();
InputStream filecontent = item.getInputStream();
String s = filecontent.toString();
out.println("<h1>"+s+" / "+filename+"</h1>");
item.write(null);
}
}
}
catch (FileUploadException e)
{
throw new ServletException("Cannot parse multipart request.", e);
}
catch (Exception e)
{
e.printStackTrace();
}
out.println("</body></html>");
}
Not providing the file path is a security feature of the browser.
You have the file contents available in your code (InputStream filecontent) so you could use that or use one of the convenience methods on FileItem, e.g.
item.write(new File("/path/to/myfile.txt"));

how to display image which is outside server directory in strtus

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
Hi Below is the answer to my question, I have created ImageServlet for displaying image, steps to perform:
1. you need to add mapping in web.xml file:
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/ImageServlet/*</url-pattern>
2. create ImageServlet:
public class ImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//Setting image path
ImageLocationService locationService = new ImageLocationService();
try {
String imageCategory = request.getParameter("imageCategory");
if (imageCategory != null) {
this.imagePath = locationService.getImageLocation(imageCategory);
}else{
this.imagePath = ConfigConstants.imageLocation;
}
} catch (Exception e) {
e.printStackTrace();
}
// Get requested image by path info.
String requestedImage = request.getPathInfo();
// Check if file name is actually supplied to the request URI.
if (requestedImage == null) {
// Do your thing if the image is not supplied to the request URI.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Decode the file name (might contain spaces and on) and prepare file object.
File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));
// Check if file actually exists in filesystem.
if (!image.exists()) {
// Do your thing if the file appears to be non-existing.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Get content type by filename.
String contentType = getServletContext().getMimeType(image.getName());
// Check if file is actually an image (avoid download of other files by hackers!).
// For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
if (contentType == null || !contentType.startsWith("image")) {
// Do your thing if the file appears not being a real image.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(image), 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.
close(output);
close(input);
}
}
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
// Do your thing with the exception. Print it, log it or mail it.
e.printStackTrace();
}
}
}
}
3. At jsp side you need to add the mapping in step 1 in your img tag i.e. input type='image':
<input type="image" alt='No image found' src='../ImageServlet/append image name that you want to display' />
You can even create Action class and use execute method for doing the same.
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.

Link doesn't work when I access it via localhost

The following servlet creates a directory named Shared and then copies the video into this directory.Next it presents the link,to download this video. But when I click the link,nothing happens. Why is this ?
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String path = request.getServletContext().getRealPath("/") + "Shared/" + "sweet-love-story-that-might-make-your-day[www.savevid.com].3gp";
path = path.replace("\\","/");
try {
File f = new File(request.getServletContext().getRealPath("/") + "Shared/");
if(!f.exists()) {
f.mkdir();
// now copy the animation to this directory
} else {
System.out.println("directory already made");
}
writer.println("<html> <head> <title> </title> </head>");
writer.println("<body>");
writer.println("Click to download");
writer.println("</body>");
writer.println("</html>");
}catch(Exception exc) {
exc.printStackTrace();
}
}
Ironically when I write a html that is in the same directory as the video (in Shared) I am able to download/see the video. Why doesn't the link work when I access it via localhost ?
(I am using Tomcat)
**Note: The statement request.getServletContext().getRealPath("/") prints W:\UnderTest\NetbeansCurrent\App-1\build\web**
The following are the snapshots of html accessed from localhost and locally respectively.
and

Categories