我想要一个java代码,它应该使用JAX-RS( Jersey )将任何类型的文件作为流返回到客户端。
我有以下代码,
@GET
@Path("/{name}")
@Produces("*/*")
public Response getFile(String name) {
File file = new File("/path/of/the/file");
FileInputStream fiS = new FileInputStream(file);
StreamingOutput st = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException {
try {
int n;
byte[] buffer = new byte[1024];
while ((n = fis.read(buffer)) >= 0) {
os.write(buffer, 0, n);
}
os.close();
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
ResponseBuilder response = Response.ok(st);
response.header("Content-Type", "*/*");
response.header("Content-Disposition", "inline; filename=" + fileName);
return response.build();
}
但它仅适用于 .txt、.html、.properties 和 .rtf
。因为我可以在客户端下载并获取这些文件类型的文件的实际内容。
但不适用于扩展名为 .doc、.pdf、.png、.PNG、.jpeg、.mp3、.mp4
..etc 的文件。
但我想要一个应该返回任何类型文件的通用代码。
返回图像时输出获取。 Image.PNG 尝试使用 content-type "image/png"
谁能帮我解决这个问题吗?
最佳答案
您必须以参数方式渲染 response.header("Content-Type", mimeType)
行,为每个响应设置合适的内容类型。您可以将其处理为映射“extension-file”->“mime-type”,如下所示:
//init in a run-once method (static, singleton, etc)
final Hashtable<String, String> allowedTypes = new Hashtable<String, String>();
allowedTypes .put("xls", "x-msexcel");
allowedTypes .put("xlsx", "application/vnd.ms-excel.12");
allowedTypes .put("mp3", "audio/mpeg3");
allowedTypes .put("doc", "application/msword");
//and so on, in a sort of white-list of allowed types
//use the map
final String default = "text/plain";
String extension = getExtension(file); //not of interest here
String curType = allowedTypes.get(extension)!= null ? allowedTypes.get(extension) : default;
response.header("Content-Type", curType);
关于java - 如何编写服务器端 java 代码以使用 JAX-RS(Jersey) 以流形式返回任何类型的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22475881/