Jersey:根据文件扩展名或 InputStream 设置响应内容类型?
Jersey: Set response content-type based on file extension or 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"
我正在使用 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"