AngularJS + Jersey REST 文件下载
发布时间:2020-12-17 09:47:25 所属栏目:安全 来源:网络整理
导读:今天为一个客户的系统增加一个下载文件的功能,前端是AngularJS发起请求,后端用Jersey REST API返回文件,实现如下: 后端: @POST@Consumes(MediaType.APPLICATION_JSON)@Path("/report/jc")@Produces(MediaType.APPLICATION_OCTET_STREAM)public Response
今天为一个客户的系统增加一个下载文件的功能,前端是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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |