How to use JAX-RS and Angular 2+ to download a zip file

前端 未结 1 1583
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 15:39

How to download a zip file exposed by a JAX-RS resource and serve it to the user with Angular2 final?

相关标签:
1条回答
  • 2021-01-07 16:05

    Given a JAX-RS resource as:

    @Produces({MediaType.APPLICATION_JSON})
    @Consumes({MediaType.APPLICATION_JSON})
    @Path("/myresource")
    public class MyResource {
    
        @Inject
        MyFacade myFacade;
    
        @POST
        @Path("/download")
        @Produces({"application/zip"})
        public Response download(@NotNull Request req) {
            byte[] zipFileContent = myFacade.download(req);
            return Response
                .ok(zipFileContent)
                .type("application/zip")
                .header("Content-Disposition", "attachment; filename = \"project.zip\"")
                .build();
        }
    }
    

    In order to consume and serve the file to an end user using a Angular2 application, we can use a service as:

    ...//other import statements
    import fileSaver = require("file-saver");
    
    @Injectable()
    export class AngularService {
    
        constructor(private http: Http) {
        }
    
        download(model: MyModel) {
            this.http.post(BASE_URL + "myresource/download", JSON.stringify(model), {
                method: RequestMethod.Post,
                responseType: ResponseContentType.Blob,
                headers: new Headers({'Content-type': 'application/json'})
            }).subscribe(
                (response) => {
                    var blob = new Blob([response.blob()], {type: 'application/zip'});
                    var filename = 'file.zip';
                    fileSaver.saveAs(blob, filename);
            }
        );
    }
    

    For this to work the fileSaver should be imported in package.json as:

    "dependencies": {
        // all angular2 dependencies... 
        "file-saver": "1.3.2"
     },
    

    And that service can be now injected on any component that requires access to the download method

    0 讨论(0)
提交回复
热议问题