使用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")