如何使用相对于Jersey中的上下文根的路径来读取文件?

时间:2012-04-02 19:01:53

标签: java rest jersey

我正在使用Jersey学习REST。我成功地创建了陈词滥调的Hello World应用程序。现在(仅用于学习目的)我试图通过字节流返回图像文件。但是,我得到一个IOException无法读取该文件。以下是我的资源类:

@Path("/image/{file}")
public class ImageResource
{
   @Context
   private UriInfo uri;

   @GET
   @Produces("image/jpg")
   public Response getFullImage(@PathParam("file") String fileName)
   {
      Response response = null;
      String contextRoot = getUri().getBaseUri().toString();

      try
      {
         BufferedImage image = ImageIO.read(new File(contextRoot + "/images/" + fileName));
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ImageIO.write(image, "jpg", baos);
         byte[] imgBytes = baos.toByteArray();

         response = Response.ok(new ByteArrayInputStream(imgBytes)).build();
      }
      catch (IOException e)
      {
         System.err.println("Error reading image file..." + e.getMessage());
         e.printStackTrace();
      }

      return response;
   }

   private UriInfo getUri() {
      return uri;
   }

}

图片存储在WebContent/images/image001.jpg下,我使用网址:http://localhost:8080/REST/image/image001.jpg来点击资源。

有人可以让我知道异常的原因???

2 个答案:

答案 0 :(得分:0)

由于资源已嵌入war / jar中,您需要使用ClassLoader为您加载:

类似的东西:

@Path("/image/{file}")
public class ImageResource
{
   @Context
   private UriInfo uri;

   @GET
   @Produces("image/jpg")
   public Response getFullImage(@PathParam("file") String fileName)
   {
      Response response = null;
      String contextRoot = getUri().getBaseUri().toString();

      try
      {
         // load resource via classloader since it's embedded in war/jar
         BufferedImage image = ImageIO.read(ImageResource.class.
                                 getResourceAsStream(/images/" + fileName));
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ImageIO.write(image, "jpg", baos);
         byte[] imgBytes = baos.toByteArray();

         response = Response.ok(new ByteArrayInputStream(imgBytes)).build();
      }
      catch (IOException e)
      {
         System.err.println("Error reading image file..." + e.getMessage());
         e.printStackTrace();
      }

      return response;
   }

   private UriInfo getUri() {
      return uri;
   }

}

答案 1 :(得分:0)

您应该以URL的形式访问该图像。 对我来说,这很有效:

String path=uriInfo.getBaseUri().toString();
            path=path.substring(0, path.lastIndexOf("/rest"))+"/img/"+foto;
            try {
                URL pathUrl=new URL(path);
                BufferedImage image=ImageIO.read(pathUrl);
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                ImageIO.write(image, "jpg", baos);
                byte[] imgBytes=baos.toByteArray();
                 return  Response.ok(new ByteArrayInputStream(imgBytes)).build();
            }

请确保您不包含其余路径。