简体   繁体   English

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

[英]Jersey: Set response content-type based on file extension or InputStream?

I am using Jersey to serve a bunch of media-type files from resource folder inside a Jar file. 我正在使用Jersey从Jar文件中的资源文件夹中提供一堆媒体类型的文件。 I have the file URL returned by getClassLoader().getResource() and the InputStream returned by getClassLoader().getResourceAsStream() , is there a way for Jersey to detect the content-type for this file? 我有getClassLoader().getResource()返回的文件URL和getClassLoader().getResourceAsStream()返回的InputStream.getResourceAsStream getClassLoader().getResourceAsStream() ,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();
  }
}

At the second TODO you can use (if Java 7): 在第二个TODO,您可以使用(如果Java 7):

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

to retrieve the mimeType. 检索mimeType。

I didn't find a solution using Jersey. 我没有找到使用Jersey的解决方案。 But I found Apache Tika works perfectly in this case, simply do 但我发现Apache Tika在这种情况下运行得很好,就这么做了

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

where path is the abstract file path, like "index.html, ui.js, test.css" 其中path是抽象文件路径,例如“index.html,ui.js,test.css”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM