RESTful creates binary

I use CXF and Spring to create RESTful web services.

This is my problem: I want to create a service that creates "any" type of file (maybe an image, a document, txt or even a PDF), as well as XML. So far I have received this code:

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

I do not know where to start, please be patient.

EDIT:

Full Bryant Luke code (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(); } 
+8
java rest binaryfiles cxf
source share
2 answers

If it returns any file, you might want to make your method more generic and return javax.ws.rs.core.Response, which can be programmatically configured for the Content-Type header:

 @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(); } 
+15
source share

We also use CXF and Spring, and this is my preferred API.

 import javax.ws.rs.core.Context; @Path("/") public interface ContentService { @GET @Path("/download/") @Produces(MediaType.WILDCARD) InputStream getFile() throws Exception; } @Component public class ContentServiceImpl implements ContentService { @Context private MessageContext context; @Override public InputStream getFile() throws Exception { File f; String contentType; if (/* want the pdf file */) { f = new File("...pdf"); contentType = MediaType.APPLICATION_PDF_VALUE; } else { /* default to xml file */ f = new File("custom.xml"); contentType = MediaType.APPLICATION_XML_VALUE; } context.getHttpServletResponse().setContentType(contentType); context.getHttpServletResponse().setHeader("Content-Disposition", "attachment; filename=" + f.getName()); return new FileInputStream(f); } } 
0
source share

All Articles