java - 如何编写服务器端 java 代码以使用 JAX-RS(Jersey) 以流形式返回任何类型的文件?

标签 java rest file-io jersey jax-rs

我想要一个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" enter image description here

谁能帮我解决这个问题吗?

最佳答案

您必须以参数方式渲染 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/

相关文章:

Java:TreeSet 的问题

java - 为什么在切换 fragment 时,recyclerview 丢失了?

java - 在以 JSON 格式发布到 API 时,如何正确发送值中包含 double 和字符串的 HashMap

java - 将控制台消息从 Eclipse 写入文件

c++ - 执行系统命令很慢

java - Qartz 正则表达式接受 cron 但不会从中构建作业

java - 使用 iTextPdf 将 HTML 转换为 PDF : java. lang.NoSuchMethodError

rest - 使用 HTTPS 的持久连接不起作用

java - 来自 @PathVariable Java Spring 的不完整文本

c++ - 使用 zlib 优化文件写入?