如何使用JAX-RS和Angular 2+下载zip文件

时间:2016-09-25 18:38:13

标签: angular java-ee download jax-rs

如何下​​载由JAX-RS资源公开的zip文件并将其提供给Angular2 final的用户?

1 个答案:

答案 0 :(得分:5)

将JAX-RS资源指定为:

@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();
    }
}

为了使用Angular2应用程序为最终用户使用和提供文件,我们可以使用以下服务:

...//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);
        }
    );
}

为了实现这一点,fileSaver应该在package.json中导入为:

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

现在,该服务可以注入需要访问download方法的任何组件