0

I am trying to display an image throw jsp. Image is stored in local path so I wrote a servlet get method to retrive image and in src attribute of image tag I am giving the servlet name and image path as parameter to servlet and here is my code,

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();

    // Check if file is actually supplied to the request URI.
    if (requestedFile == null) {
        // Do your thing if the file is not supplied to the request URI.
        // Throw an exception, or send 404, or show default/warning page, 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 file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName());

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // Init servlet response.
    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() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), 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);
    }
}

protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("In do post");

}


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();
        }
    }
}

in web.xml the servlet entry is as follow,

<servlet>
<description>
</description>
<display-name>FileServlet</display-name>
<servlet-name>FileServlet</servlet-name>
<servlet-class>com.mypackage.FileServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/file/*</url-pattern>
</servlet-mapping>

In Jsp I have img tag as follow,

<img alt="Image" src="file/D:/uploads/img14.jsp" width="160" height="160"    class="img-thumbnail">

I think I made mistake in src attribute of img tag can anyone tell wht is the mistake I made here .

user3599482
  • 157
  • 2
  • 3
  • 15
  • 1
    That's something you should be able to debug by yourself. Use your debugger, or even System.out.printlns, to know what the value of `requestedFile` and `file` are. Beware of the huge security hole that you could be opening with that kind of servlet. You don't want to allow any user to access any file on your server. Also, .jsp is a strange extension for an image. – JB Nizet May 04 '14 at 16:22

4 Answers4

3

Looks like you have misunderstood BalusC's post about this: FileServlet. In this case, you will have a base path in your disk to server your files (external to the web application folder path in server), and then the path used in your URL will be used to search inside this base path. Note from BalusC's example how to call the resources:

<a href="file/foo.exe">download foo.exe</a>

Where:

  • file is the URL pattern for your Servlet. Noted in your web.xml configuration:

    <servlet-mapping>
    <servlet-name>FileServlet</servlet-name>
    <url-pattern>/file/*</url-pattern>
    </servlet-mapping>
    
  • The rest of the URL /foo.exe is the location of the file in your server hard drive. This can be easily obtained by usage of HttpServletRequest.html#getPathInfo

This is noted by this part of the code (comments are mine):

public void init() throws ServletException {
    this.filePath = "/files";
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // Get the file path from the URL.
    String requestedFile = request.getPathInfo();

    //...
    //using filePath attribute in servletclass as the base path
    //to lookup for the files, using the requestedFile
    //path to seek for the existance of the file (by name)
    //in your server
    //decoding the name in case of GET request encoding such as
    //%2F => /
    File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
    //...
}

Then, when having a request like this (in HTML code in your view):

<img src="files/img/myimage.png" />

You have to make sure the file exists in your server:

- /  <-- root
  - /files <-- this is the base file path set in init method in your servlet
    - /img
      - myimage.png

More info:

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • no. , I am not getting what you are saying exactly , please tell me what should be my src attribute value or tell me do I need to change anything in my FileServlet? – user3599482 May 05 '14 at 06:33
  • I said my image in local drive, I mean in D:/uploads/Img.jpg path. – user3599482 May 05 '14 at 15:44
  • @user3599482 and I've said that **doesn't matter** for your Servlet. **Do not** carelessly/blindly copy/paste some code on the net without reading it and understanding it. I have even posted an example of how you can place an `` and where the servlet fill try to find it. If you know all your files will be inside *D:/uploads* then change `filePath` value in your servet from `"/files"` to `"D:\\uploads"`. – Luiggi Mendoza May 05 '14 at 15:50
0

The mistake you made is trying to call your JSP page as an image resource. The JSP itself is just a text file. You need to substitute the path to the file with a url to the page on a server that will compile/serve the results of the JSP page, namely the image. If it's on a local server, typically the url will look like http://localhost:<port>/.../img14.jsp.

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159
0

Your src attribute of img tag should be like this to send request to your servlet. src="${pageContext.request.contextPath}/FileServlet/getImage?path=D:\offline_registration\11022017\unzip\a89a89e9-5de2-4bb2-9225-e465bb5705b1.jpeg"

here path variable contains path of image from local system.

-1

I have tried below code and it works fine in both servlet and java. If the image is converted as byte in servlet using the code below then set the converted byte code in session attribute and get it jsp.

Note: it can display any format of image

package Jx_Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;

public class Imag {

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        // TODO Auto-generated method stub
         File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");

            FileInputStream fis = new FileInputStream(file);
            //create FileInputStream which obtains input bytes from a file in a file system
            //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            try {
                for (int readNum; (readNum = fis.read(buf)) != -1;) {
                    //Writes to this byte array output stream
                    bos.write(buf, 0, readNum); 
                    System.out.println("read " + readNum + " bytes,");
                }
            } catch (IOException ex) {
               // Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
            }

            byte[] bytes = bos.toByteArray();

            byte[] encodeBase64 = Base64.encodeBase64(bytes);
            String base64Encoded = new String(encodeBase64, "UTF-8");


            System.out.println(base64Encoded);
    }

}

//Jsp
<img src="data:image/jpeg;base64,<%=base64Encoded%>"/>
zapping
  • 4,118
  • 6
  • 38
  • 56