是否可以从Jersey Rest服务控制响应的文件名?

dal*_*nns 19 jax-rs jersey

目前,我在Jersey中有一个方法,它从内容存储库中检索文件并将其作为响应返回.该文件可以是jpeg,gif,pdf,docx,html等(基本上任何东西).但是,目前我无法弄清楚如何控制文件名,因为每个文件都会自动下载名称(下载.[文件扩展名]即(download.jpg,download.docx,download.pdf).有没有办法我可以设置文件名吗?我已经把它放在一个字符串中,但我不知道如何设置响应,以便它显示文件名而不是默认为"下载".

@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();
}
Run Code Online (Sandbox Code Playgroud)

小智 29

使用Jersey提供的ContentDisposition类更好的方法,更安全,更方便:

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();
Run Code Online (Sandbox Code Playgroud)

  • 在泽西岛1.17.它来自`com.sun.jersey.core.header.ContentDisposition` (2认同)

Mor*_*itz 25

您可以在响应中添加" Content-Disposition标题",例如

rb.header("Content-Disposition",  "attachment; filename=\"thename.jpg\"");
Run Code Online (Sandbox Code Playgroud)