Is it possible to control the filename for a Response from a Jersey Rest service?
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 "d开发者_如何学编程ownload".
@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();
}
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();
You can add a "Content-Disposition
header" to the response, e.g.
rb.header("Content-Disposition", "attachment; filename=\"thename.jpg\"");
In the case where you aren't using the ResponseBuilder class, you can set the header directly onto the Response, which avoids any extra dependencies:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"somefile.jpg\"").build();
@GET
@Path("zipFile")
@Produces("application/zip")
public Response getFile() {
File f = new File("/home/mpasala/Documents/Example.zip");
String filename= f.getName();
if (!f.exists()) {
throw new WebApplicationException(404);
} else {
Boolean success = moveFile();
}
return Response
.ok(f)
.header("Content-Disposition",
"attachment; filename="+filename).build();
}
Here I find the solution to my problem. I appended the file name in response header.
精彩评论