taffykula
taffykula

Reputation: 576

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. 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?

Upvotes: 3

Views: 4627

Answers (2)

taffykula
taffykula

Reputation: 576

I didn't find a solution using Jersey. But I found Apache Tika works perfectly in this case, simply do

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

where path is the abstract file path, like "index.html, ui.js, test.css"

Upvotes: 1

DominikAngerer
DominikAngerer

Reputation: 6530

@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):

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

to retrieve the mimeType.

Upvotes: 2

Related Questions