简体   繁体   中英

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). 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 . 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.

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" 在此处输入图片说明

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. You could handle it as a map " extension-file " -> " mime-type ", something like the following:

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

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.

Ex: To know the file extension of the byte[], just add to code above:

mimeType.getExtension()

This will return : .pdf, .xml, .txt ...

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM