TaouBen
TaouBen

Reputation: 1315

Impossible to load image in jsp?

I am having this little problem, I see that it is impossible to load picture in my console, I don't know how to solve the problem.

I am getting my image name from database as a String in my controller, just the name, something like that ' image.jpg' and it is stored in my folder 'images'.

Here is my jsp file :

<c:if test="${ !(post.cover == 'empty')}">
   <div class="imgPub">
     <img src="Assets/images/${post.cover }">
   </div>
</c:if>

In my inspector i can see the whole src written exactly, but a message next to it saying impossible to load image.

Any help would be much appreciated.

Upvotes: 1

Views: 261

Answers (1)

Milkmaid
Milkmaid

Reputation: 1754

HttpServlet will do the job.

use:

youraddress.xxx/images/filename.png

this is important @WebServlet("/images/*")

It will automatically leads to folder defined in PATH and retrieve the image based on the name.

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {

public static final String PATH = "C:/"
/*
linux
public static final String PATH = "/home/images/"
*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getPathInfo().substring(1);
        File file = new File(PATH,filename);
        response.setHeader("Content-Type", getServletContext().getMimeType(filename));
        response.setHeader("Content-Length",String.valueOf(file.length()));
        response.setHeader("Content-Disposition","inline; filename=\""+filename +"\"");
        Files.copy(file.toPath(),response.getOutputStream());
    }

}

Upvotes: 1

Related Questions