Issue
My web Java project with servlets/jsp can upload images (even thought is not the best way), but when I try to show the images in a table (using JSTL), there's just a blank image, like the url of image is broken. But when I copy the url image and paste in the browser's address bar, the image is shown as expected. The url is like this:
file:///c:/Users/user/Documents/NetBeansProjects/Project1/target/Project-1.0-SNAPSHOT//images/image1.png
This is how is set on the JSP page:
<img src="<c:out value="${requestScope.path}" /><c:out value="${test.image}" />" />
Thanks in advance!
Solution
When you type a URL with a file protocol into your browser's address bar, your browser asks your operating system for the file. When you put that same URL into a img tag on a HTML page, the browser now makes a HTTP request for the file. But, the file is not accessible over the internet. In order to do what want to do, you must have a Servlet read the file from the file system and then put it into a HTTP response that can be sent when the browser requests the image. Here is demonstration code.
package rick;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
@WebServlet("/serveImage")
public class ServeImage extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpeg");
FileInputStream fis = new FileInputStream("C:/Users/rick/Documents/RickProfile.jpeg");
fis.transferTo(response.getOutputStream());
}
}
and request it with an img tag like
<img src="serveImage" />
Answered By - rickz
Answer Checked By - Clifford M. (JavaFixing Volunteer)