Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to control the filename for a Response from a Jersey Rest service?

Tags:

Currently I have a method in Jersey that retrieves a file from a content repository and returns it as a Response. The file can be a jpeg, gif, pdf, docx, html, etc. (basically anything). Currently, however, I cannot figure out how I can control the filename since each file downloads automatically with the name (download.[file extension] i.e. (download.jpg, download.docx, download.pdf). Is there a way that I can set the filename? I already have it in a String, but I don't know how to set the response so that it shows that filename instead of defaulting to "download".

@GET
@Path("/download/{id}")
public Response downloadContent(@PathParam("id") String id)
{
    String serverUrl = "http://localhost:8080/alfresco/service/cmis";
    String username = "admin";
    String password = "admin";

    Session session = getSession(serverUrl, username, password);

    Document doc = (Document)session.getObject(session.createObjectId(id));

    String filename = doc.getName();

    ResponseBuilder rb = new ResponseBuilderImpl();

    rb.type(doc.getContentStreamMimeType());
    rb.entity(doc.getContentStream().getStream());

    return rb.build();
}
like image 565
dallinns Avatar asked Mar 15 '11 21:03

dallinns


People also ask

What is the use of Jersey in Java?

Jersey is Sun's production quality reference implementation for JSR 311: JAX-RS: The Java API for RESTful Web Services. Jersey implements support for the annotations defined in JSR-311, making it easy for developers to build RESTful web services with Java and the Java JVM.

What is Jax-RS and Jersey?

JAX-RS is an specification (just a definition) and Jersey is a JAX-RS implementation. Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides its own API that extend the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development.


1 Answers

An even better way, which is more typesafe, using the Jersey provided ContentDisposition class:

ContentDisposition contentDisposition = ContentDisposition.type("attachment")
    .fileName("filename.csv").creationDate(new Date()).build();

 return Response.ok(
            new StreamingOutput() {
                @Override
                public void write(OutputStream outputStream) throws IOException, WebApplicationException {
                    outputStream.write(stringWriter.toString().getBytes(Charset.forName("UTF-8")));
                }
            }).header("Content-Disposition",contentDisposition).build();
like image 198
user2310417 Avatar answered Sep 21 '22 07:09

user2310417