Jersey:根据文件扩展名或InputStream设置响应内容类型



我使用Jersey从Jar文件中的资源文件夹中提供一堆媒体类型的文件。我有getClassLoader().getResource()返回的文件URL和getClassLoader().getResourceAsStream()返回的InputStream,Jersey有办法检测这个文件的content-type吗?

@GET
@Path("/attachment")
@Consumes("text/plain; charset=UTF-8")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getAttachment(
  @QueryParam("file") String fileName) {
  try {
    if (fileName == null) {
      System.err.println("No such item");
      return Response.status(Response.Status.BAD_REQUEST).build();
    }
    StreamingOutput stream = new StreamingOutput() {
      @Override
      public void write(OutputStream output) throws IOException {
        try {
          // TODO: write file content to output;
        } catch (Exception e) {
           e.printStackTrace();
        }
      }
    };
    return Response.ok(stream, "image/png") //TODO: set content-type of your file
            .header("content-disposition", "attachment; filename = "+ fileName)
            .build();
    }
  }
  System.err.println("No such attachment");
  return Response.status(Response.Status.BAD_REQUEST).build();
  } catch (Exception e) {
     System.err.println(e.getMessage());
     return Response.status(Response.Status.BAD_REQUEST).build();
  }
}

在第二个TODO中,您可以使用(如果是Java 7):

Path source = Paths.get("/images/something.png");
Files.probeContentType(source);

以检索mimeType。

我没有找到使用Jersey的解决方案。但我发现Apache Tika在这种情况下非常有效,只需执行

    Tika tika = new Tika();
    String contentType = tika.detect(path);

其中path是抽象文件路径,如"index.html,ui.js,test.css"

最新更新