正在提供我的战争目录中的图片? [英] Serving an image from my war directory?

查看:91
本文介绍了正在提供我的战争目录中的图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Servlet,它提供一个存储在Blob中的图像文件.如果找不到所请求的图像,那么我想服务器存储在war目录中的静态图像.我们如何做到这一点?这就是我从数据存储中投放Blob图片的方式:

I have a servlet which serves an image file which was stored in a blob. If the requested image can't be found, I'd like to server a static image I have included in my war directory. How do we do this? This is how I'm serving the blob images from the datastore:

public class ServletImg extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
  {
    MyImgWrapper obj = PMF.get().getPersistenceManager().
      getObjectById(MyImgWrapper.class, 'xyz');
    if (obj != null) {
      resp.getOutputStream().write(obj.getBlob().getBytes());
      resp.getOutputStream().flush();
    }
    else {
      // Here I'd like to serve an image from my war file. 
      /war/img/missingphoto.jpg
    } 
  }
}

是的,我只是不确定如何从我的战争目录中的图像中获取图像字节,或者是否还有其他方法可以做到这一点?

yeah I'm just not sure how to get the image bytes from the image in my war dir, or if there's some other way to do it?

谢谢

推荐答案

其他答案推荐webcontent 获取图像. (java.lang.String)" rel ="nofollow noreferrer"> ServletContext#getResourceAsStream() .继承的

The other answers recommending ClassLoader#getResourceAsStream() are expecting that the image is located in the classpath. You can however also obtain the image from the webcontent using ServletContext#getResourceAsStream(). The ServletContext is available in servlets by the inherited getServletContext() method.

InputStream input = getServletContext().getResourceAsStream("/img/missingphoto.jpg");


也就是说,完全从byte[]中读取和写入实际上不是高效的内存.考虑通过小字节缓冲区(1〜10KB)进行流式传输,如下所示:


That said, reading and writing fully into/from a byte[] is not really memory efficient. Consider streaming through a small byte buffer (1~10KB) like so:

input = getServletContext().getResourceAsStream(path);
output = response.getOutputStream();
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
    output.write(buffer, 0, length);
}

这篇关于正在提供我的战争目录中的图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆