您的位置:首页 > 其它

jersey 实现文件下载(以ms word 为例)

2015-07-10 14:27 357 查看
使用Jersey难免会碰到下载文件这样的需求,其实实现起来很简单,以微软word文档为例,代码片段如下:

@GET
@Path("download/document")
@Produces("application/vnd.ms-word;charset=utf-8")
public Response downloadDoc(@Context HttpServletRequest request,
@Context HttpServletResponse response,
@QueryParam("id") String id){
String filepath = "D:/test.doc";
String filename = filepath.substring(filepath.lastIndexOf("/")+1);

File downloadFile = new File(filepath);
ResponseBuilder responseBuilder = Response.ok((Object) downloadFile);
try {
responseBuilder.header("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseBuilder.build();
}


其中:@Produces("application/vnd.ms-word;charset=utf-8") 的 “application/vnd.ms-word” 官方文档并没有,但是官方文档有“application/vnd.ms-excel”,因此把excel改成word,试验的结果是成功的。另外 java.net.URLEncoder.encode(filename, "UTF-8") 是确保中文文件名不会乱码。

其他类型的文件下载实现相似,只需要修改@Produces 和文件名即可;

.txt ---> @Produces("text/plain")

.pdf ---> @Produces("application/pdf")

.png ----> @Produces("image/png")

.xls ----> @Produces("aapplication/vnd.ms-excel")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: