3

My code is uploading an image and saving the image to my server, but I need to display the image in my jsp page.

The jsp for uploading image

uploadImage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head><title>Image Upload</title></head>

<body>
  <form action="UploadImage" method="post" enctype="multipart/form-data" 
           name="productForm" id="productForm"><br><br>
    <table width="400px" align="center" border=0 style="background-color:ffeeff;">
      <tr>
        <td align="center" colspan=2 style="font-weight:bold;font-size:20pt;">
           Image Details</td>
      </tr>

      <tr>
        <td align="center" colspan=2>&nbsp;</td>
      </tr>

      <tr>
        <td>Image Link: </td>
        <td>
          <input type="file" name="file" id="file">
        <td>
      </tr>

      <tr>
        <td></td>
        <td><input type="submit" name="Submit" value="Submit"></td>
      </tr>
      <tr>
        <td colspan="2">&nbsp;

        </td>
      </tr>

    </table>
  </form>
</body>

</html> 

Servlet

UploadImage

public class UploadImage extends HttpServlet {
    /**
     * 
     */

    private static final long serialVersionUID = 2082405235440894340L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        File filenameImg;
        List<FileItem> items = null;
        try {
            items = new ServletFileUpload(new DiskFileItemFactory())
                    .parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException("Cannot parse multipart request.", e);
        }

        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form fields here the same way as
                // request.getParameter().
                // You can get parameter name by
                item.getFieldName();
                // You can get parameter value by item.getString();
            } else {

                try{
                    // Process uploaded fields here.
                    String filename = FilenameUtils.getName(item.getName());
                    // Get filename.
                    String path = GetWebApplicationPathServlet.getContext().getRealPath("/images");

                    File file =  new File(path,filename);


                    //File file = new File("C:\\", filename);

                    // Define destination file.

                    item.write(file);
                    System.out.println("filename: "+filename);
                    System.out.println("file: "+file);
                    request.setAttribute("image", file);
                    filenameImg = file;
                    // Write to destination file.
                //  request.setAttribute("image", filename);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        // Show result page.


        System.out.println("request"+request.getAttribute("image"));
        response.setContentType("image/jpeg"); 
        //request.getRequestDispatcher("result.jsp").forward(request, response);

        String nextJSP = "/result.jsp";
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(nextJSP);
        dispatcher.forward(request, response);

    }

}

result.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=request.getParameter("image")%>

<img src="<%=request.getParameter("image")%>">
</body>
</html>

<%=request.getParameter("image")%> is returned as null in the result.jsp page

Help

crowne
  • 8,456
  • 3
  • 35
  • 50
jennifer
  • 8,133
  • 22
  • 69
  • 96
  • Can you tell us whether you're willing to store this image at some location before preview? .. will be helpful pls answer – Premraj Apr 01 '11 at 06:59
  • @Falcon i need to store the image in my tomcar server. i have craeted a folder images in my project and the image is being saved in that particular directory, but my problem is that im not able to show that saved image in my jsp page – jennifer Apr 01 '11 at 09:49
  • You are doing it right. Now just pass path in request with name of the uploaded image. – Harry Joy Apr 01 '11 at 11:20
  • check my answer, point 1 may be helpful in this case – Premraj Apr 01 '11 at 11:46
  • 1
    Related: http://stackoverflow.com/questions/2340406/retrieve-multiple-images-from-mysql/2341322#2341322 – BalusC Apr 01 '11 at 12:03

5 Answers5

9

I'm considering you are storing a image file somewhere on the server -

  1. If that path is inside your application then you can give that path directly in the image src attribute, e.g. -
    if you're storing file somewhere like <context root>/resources/image/someImage.jpg then you can give that path (path should be inside the application which is accessible via browser with your context rrot) image src attribute and browser will point to that image.
  2. You can store the file somewhere in the server (outside of the application say "d:\someImage.jpg") then this cannot be reachable by the browser directly but you can still show that image via servlet, e.g. -
    you can write a new servlet and in the goGet method you can read the image file and write it to the response output stream. give this servlet url in the src of the image like -

e.g.

<image src="context root/displayServlet?image=someImage.jpg">


The servlet code may look like -
EDIT: - For better code refer How to retrieve and display images from a database in a JSP page?

try{
         String fileName = request.getParameter("image");             
         FileInputStream fis = new FileInputStream(new File("d:\\"+fileName));
         BufferedInputStream bis = new BufferedInputStream(fis);             
         response.setContentType(contentType);
         BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
         for (int data; (data = bis.read()) > -1;) {
           output.write(data);
         }             
      }
      catch(IOException e){

      }finally{
          // close the streams
      }

You can improve this code, I'm just giving an example.

Community
  • 1
  • 1
Premraj
  • 7,802
  • 8
  • 45
  • 66
2

<img src="<%=request.getParameter("image")%>">

First of all src of img tag only takes image path as string so you can not pass whole image in it.

Now what you can do is:-- When you are uploading image on server don't save/pass whole image file in request instead only add the path of image in request where you upload image. In your code path is path + *file separator* + filename. Pass this to src of img tag and it will do the trick. Here file separator can be "/" or "\\".

Hope this helps.


As suggested by BalusC in comment It's better to use <img src="${param.image}" />.

Community
  • 1
  • 1
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • You are wrong about the second thing. HTML and JSP scriptlet does not run in sync or something. – BalusC Apr 01 '11 at 11:56
  • @BalusC: so you mean to say it will not give any error if we write like this: `">` – Harry Joy Apr 01 '11 at 11:59
  • Correct. Maybe buggy editors do (either by warnings or suggestive highlighting), but it's technically perfectly fine. Try it yourself. You're probably confusing with mixing HTML with JavaScript. Since they runs both at client machine, quoting matters. – BalusC Apr 01 '11 at 12:00
  • @BalusC: you are right. Thnx. let me update my answer. – Harry Joy Apr 01 '11 at 12:06
  • It is **not better** to use it that way. Using `` is way much better. – BalusC Apr 01 '11 at 12:09
  • I did not mean to imply that this is *the* answer. It's just the style. – BalusC Apr 01 '11 at 12:17
  • @BalusC: If its better option than it must be in answer as a suggestion. – Harry Joy Apr 01 '11 at 12:18
1

There are two mistakes to the approach you have taken. First, in the above servlet code you have coded as if you are downloading an image file (You have set the content type as image.

Second, you have in no way associated the image file to response. Not through a image parameter or through a stream.

Now, since you have mixed up two approaches.. you need to decide what you need first. From your explanation, I understand that you are trying to display the uploaded image in the result.jpg. In that case, you don't need to send the image with content type set. In your result.jsp, the img tag expects the path of the image to be displayed. So, you need to set the path of your image to "image" attribute in response.

response.setAttribute("image", imagepath);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);

the image path should be some valid URL to access the image.In your result.jsp you need:

request.getParameter("image");

to get the image. Here is how it will be:

<img src='<%=request.getParameter("image")%>'>
Abdel Raoof Olakara
  • 19,223
  • 11
  • 88
  • 133
  • i have done as u suggested and the image is being displayed in my eclipse browser. But when i took the application in my IE, the image is not shown there...Pls hep – jennifer Apr 01 '11 at 09:53
0

Jeje, the problem of null is because are diferent things; Attributes and Parameters, if you did:

request.setAttribute("image", file.getPath()); 

then you need to do:

request.getAttribute("image")
eldarerathis
  • 35,455
  • 10
  • 90
  • 93
0

In Your servlet set a request attribute which returns full path of your image to JSP.

String fullpath = path + File.separator + filename

request.setAttribute("fullpath",fullpath);

You are already forwarding request to JSP.

So, now get the attribute using

<% 

String path = "";
if(request.getAttribute("fullpath")!=null)
    path = request.getAttribute("fullpath").toString();

%>

in your JSP and then display the image using that path

<img src='<%=path%>'>
Hardik Mishra
  • 14,779
  • 9
  • 61
  • 96
  • What do you mean by full path? if the image is stored on 'd' drive then full path would be 'd:\someImage.jpg'.. is that what you mean? if so then it won't work. – Premraj Apr 01 '11 at 06:23