显示项目文件夹jsf glassfish之外的图像

时间:2014-11-15 22:00:22

标签: java jsf jsf-2 glassfish

我想向用户展示一些图片,这些图片位于此处:

C:\Users\advert_images

我正在使用primefaces并使用servelet显示:

   @WebServlet("/advert_images/*")
public class ImagesServlet extends HttpServlet {

    @Override
    protected
            void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getPathInfo().substring(1);
        File file = new File("C:\\Users\\advert_images\\", 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());
    }

}

所以当我输入浏览器时:

http://localhost:8080/vas-plus/advert_images/3.jpg

我得到了我的形象。

但是当我尝试用我的xhtml写作时

 <img src ="http://localhost:8080/vas-plus/advert_images/3.jpg"/>

或者:

 <h:graphicImage class="test" value="/advert_images/3.jpg"/>

我没有显示图像。还有这个作为html输出:

<img src="/vas-plus/advert_images/3.jpg" class="test" width="0" height="0" style="display: none !important; visibility: hidden !important; opacity: 0 !important; background-position: 1px 1px;">

当我使用Google Chrome developerTools查看html页面的资源时,我看到了这一点: enter image description here

所以我对任何想法都有些困惑?

1 个答案:

答案 0 :(得分:0)

似乎错误的Content Type标头,可能是因为ServletContext无法访问您的文件(不确定)。

试试这个:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String filename = request.getPathInfo().substring(1);
    File file = new File("C:\\Users\\advert_images\\", filename);
    response.setContentType("image/jpeg");
    response.setContentLength((int) file.length());
    FileInputStream in = new FileInputStream(file);
    OutputStream out = response.getOutputStream();
    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }
    out.close();
    in.close();
}

我强烈建议您将文件放入项目中。