Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful produces binary file

I'm new using CXF and Spring to make RESTful webservices.

This is my problem: I want to create a service that produces "any" kind of file(can be image,document,txt or even pdf), and also a XML. So far I got this code:

@Path("/download/")
@GET
@Produces({"application/*"})
public CustomXML getFile() throws Exception; 

I don't know exactly where to begin so please be patient.

EDIT:

Complete code of Bryant Luk(thanks!)

@Path("/download/")
@GET
public javax.ws.rs.core.Response getFile() throws Exception {
    if (/* want the pdf file */) {
        File file = new File("...");
        return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
            .header("content-disposition", "attachment; filename =" + file.getName())
            .build(); 
    }

    /* default to xml file */
    return Response.ok(new FileInputStream("custom.xml")).type("application/xml").build();
}
like image 888
Marco Aviles Avatar asked Oct 04 '11 00:10

Marco Aviles


1 Answers

If it will return any file, you might want to make your method more "generic" and return a javax.ws.rs.core.Response which you can set the Content-Type header programmatically:

@Path("/download/")
@GET
public javax.ws.rs.core.Response getFile() throws Exception {
    if (/* want the pdf file */) {
        return Response.ok(new File(/*...*/)).type("application/pdf").build(); 
    }

    /* default to xml file */
    return Response.ok(new FileInputStream("custom.xml")).type("application/xml").build();
}
like image 193
Bryant Luk Avatar answered Oct 21 '22 01:10

Bryant Luk