代码之家  ›  专栏  ›  技术社区  ›  taffykula

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

  •  3
  • taffykula  · 技术社区  · 10 年前

    我使用Jersey来提供Jar文件中资源文件夹中的一堆媒体类型文件。文件URL由 getClassLoader().getResource() 以及由返回的InputStream getClassLoader().getResourceAsStream() ,Jersey有没有办法检测 content-type 对于此文件?

    2 回复  |  直到 10 年前
        1
  •  2
  •   DominikAngerer    10 年前
    @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。

        2
  •  1
  •   taffykula    10 年前

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

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

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