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

Ser*_*gio 0 jax-rs download java-ee angular

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

Ser*_*gio 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

为了使用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);
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

要使其工作,fileSaver应将其导入package.json为:

"dependencies": {
    // all angular2 dependencies... 
    "file-saver": "1.3.2"
 },
Run Code Online (Sandbox Code Playgroud)

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