我正在使用 dropwizard 进行我的 rest api 开发,它返回 json 响应。我现在遇到了一个要求,我必须在调用一个特定的 api 时返回一个 excel 文件。我发现 apache poi 是一个很好的库。但是我如何将 excel 文件作为响应返回。然后浏览器应该显示一个下载选项。
最佳答案
将 Content-Type 设置为 application/octet-stream
并添加 Content-Disposition
响应 header 应该这样做。像 Content-Disposition: attachment; filename="file.xsl"
.例如
@Path("/file")
public class FileResource {
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() throws Exception {
InputStream is = new FileInputStream("file.txt");
return Response.ok(is)
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"file.txt\"")
.build();
}
}
除了
InputStream
, 你可以返回 File
, 一个 byte[]
, 一个 StreamingOutput
,你有选择。
关于excel - 如何使用 dropwizard 将响应作为 excel 文件返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31488703/