[英]Jersey: Set response content-type based on file extension or InputStream?
我正在使用Jersey從Jar文件中的資源文件夾中提供一堆媒體類型的文件。 我有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();
}
}
在第二個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”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.