今天为一个客户的系统增加一个下载文件的功能,前端是AngularJS发起请求,后端用Jersey REST API返回文件,实现如下:
后端:
@POST @Consumes(MediaType.APPLICATION_JSON) @Path("/report/jc") @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response downloadReport() { File dir = new File("custom/hangzhou_jw"); if(!dir.exists()){ dir.mkdirs(); } File export = new File(dir.getAbsolutePath() + "/export.doc"); //默认在项目根目录下 if(!export.exists()){ try{ export.createNewFile(); }catch(IOException e){ System.out.println("创建文件失败"); } } String mt = new MimetypesFileTypeMap().getContentType(export); return Response .ok(export,mt) .header("Content-disposition","attachment;filename=export.doc") .build(); }
前端:
$http.post(fs.common.baseResourceURL + '/custom/hangzhou_jw/report/jc',postData,{responseType: "blob"}) .success(function (data) { var blob = new Blob([data],{type: "application/octet-stream"}); var fileName = "export.doc"; var a = document.createElement("a"); document.body.appendChild(a); a.download = fileName; a.href = URL.createObjectURL(blob); a.click(); })
以上是我自己的实现。
感谢这位网友的分享:http://blog.csdn.net/cjd6568358/article/details/49364255