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();
}
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With