我正在使用 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。
关于java - Jersey:根据文件扩展名或 InputStream 设置响应内容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28788379/