是否可以控制Jersey Rest服务响应的文件名?
目前我在Jersey有一个方法,它从内容存储库中检索文件并将其作为响应返回。该文件可以是jpeg、gif、pdf、docx、html等格式(基本上可以是任何格式)。但是,目前我还不知道如何控制文件名,因为每个文件都会自动下载,并带有名称(download.[文件扩展名]即(download.jpg,download.docx,download.pdf).有没有办法设置文件名?我已经有了一个字符串,但我不知道如何设置响应,使其显示该文件名,而不是默认为“下载” 您可以在响应中添加一个是否可以控制Jersey Rest服务响应的文件名?,jersey,jax-rs,Jersey,Jax Rs,目前我在Jersey有一个方法,它从内容存储库中检索文件并将其作为响应返回。该文件可以是jpeg、gif、pdf、docx、html等格式(基本上可以是任何格式)。但是,目前我还不知道如何控制文件名,因为每个文件都会自动下载,并带有名称(download.[文件扩展名]即(download.jpg,download.docx,download.pdf).有没有办法设置文件名?我已经有了一个字符串,但我不知道如何设置响应,使其显示该文件名,而不是默认为“下载” 您可以在响应中添加一个 rb.hea
rb.header("Content-Disposition", "attachment; filename=\"thename.jpg\"");
使用Jersey提供的
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();
在不使用ResponseBuilder类的情况下,可以直接将标头设置到响应上,从而避免任何额外的依赖项:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"somefile.jpg\"").build();
在这里,我找到了问题的解决方案。我在响应头中添加了文件名。ContentDisposition来自
org.glassfish.jersey.media
/jersey media multipart
,如果在客户端和服务器之间专门使用JSON,则可能还没有。在jersey 1.17中,它来自com.sun.jersey.core.header.ContentDisposition
我无法将此字符串附加到内容处置标题filename*=UTF-8“url\u encoded\u filename
。你知道为什么吗?
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();
}