简体   繁体   English

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

[英]How can I write a server side java code to return any kind of file as stream using JAX-RS(Jersey)?

I want a java code which should return any kind of file as stream using JAX-RS (Jersey). 我想要一个Java代码,该代码应使用JAX-RS(Jersey)作为流返回任何类型的文件 to the client side. 到客户端。

I have the following code, 我有以下代码,

@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();
}

But it works only for .txt, .html, .properties and .rtf . 但它仅适用于.txt, .html, .properties and .rtf Since I can download and get the actual content of the files in the client side for these file types. 由于我可以在客户端下载和获取这些文件类型的文件的实际内容。

But not sworking for the files with extension .doc, .pdf, .png, .PNG, .jpeg, .mp3, .mp4 ..etc. 但不要扩展名为.doc, .pdf, .png, .PNG, .jpeg, .mp3, .mp4 .mp4..etc的文件。

But I want a common code which should return any kind of files. 但是我想要一个通用代码,该代码应该返回任何类型的文件。

Output getting while returning the image. 返回图像时输出得到。 Image.PNG Tried with content-type "image/png" Image.PNG尝试使用content-type "image/png" 在此处输入图片说明

Can anyone help me to fix this? 谁能帮我解决这个问题?

You 'll have to render parametric the line response.header("Content-Type", mimeType) , setting per-response a suitable content-type. 您将必须对参数行response.header("Content-Type", mimeType)进行渲染,并为每个响应设置合适的内容类型。 You could handle it as a map " extension-file " -> " mime-type ", something like the following: 您可以将其作为地图“ 扩展文件 ”->“ mime类型 ”进行处理,如下所示:

    //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);

In addition to the answer provided by robermann, the way to know the Mime-Type of the binary to send to client can be detected using Apache Ticka 除了robermann提供的答案外,还可以使用Apache Ticka检测知道要发送给客户端的二进制文件的Mime-Type的方法。

byte[] bs = ....
final String contentType = new Tika()
         .detect(new BufferedInputStream(new ByteteArrayInputStream(bs)));
MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
MimeType mimeType = allTypes.forName(contentType);

Now you can access object MimeType and sent its type into the header. 现在,您可以访问对象MimeType并将其类型发送到标题中。

Ex: To know the file extension of the byte[], just add to code above: 例如:要知道byte []的文件扩展名,只需添加到上面的代码中:

mimeType.getExtension()

This will return : .pdf, .xml, .txt ... 这将返回:.pdf,.xml,.txt ...

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用JAX-RS从Java服务器端返回Zip文件? - How can I return a Zip file from my Java server-side using JAX-RS? 如何使用Jersey JAX-RS返回结果集? - How do I return a resultset using Jersey JAX-RS? 如何设置Jersey JAX-RS服务器端记录器级别? - How to set Jersey JAX-RS server side logger level? JAX-RS / Jersey:如何“继承” @Provider字段? - JAX-RS/Jersey: How can I “inherit” @Provider fields? 如何通过JAX-RS(Jersey)使用$ resource从AngularJS客户端使用JSON数据和文件上传向服务器发送请求? - How can I send request to the server with JSON data and fileupload from AngularJS client using $resource via JAX-RS(Jersey)? 如何使用JAX-RS返回实际的html文件 - How to return actual html file using JAX-RS 尝试将文件上传到 JAX-RS(球衣)服务器 - Trying to upload a file to a JAX-RS (jersey) server Java:用户使用带有Spring Security的Jersey Jax-RS进行身份验证 - Java: User Authenticate Using Jersey Jax-RS with Spring Security 使用Jersey JAX-RS的Java Web服务 - Java Web Service using Jersey JAX-RS 如何让JAX-RS将Java 8 LocalDateTime属性作为JavaScript样式的日期字符串返回? - How can I have JAX-RS return a Java 8 LocalDateTime property as a JavaScript-style Date String?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM