Angular 2/4 file download from web api

Your Component

this.commonService.getMultipart()
  .subscribe(blob => {
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="any name + extension";
    link.click();
  })

Service 

setMultipartHeader(headers:Headers){
headers.append('method', 'GET');
//any headers you want to set
}

getMultipart(){
var headers = new Headers();
this.setMultipartHeader(headers);
let requestOptions = new RequestOptions({
headers: headers,
responseType:ResponseContentType.Blob,//dont forget to import the enum
//In case you get Module not found: Error: Can't resolve '@angular/http/src/enums', just use 3 instead ex "responseType:3"
});

return this.http.get("url",requestOptions)
.map(res => {
return new Blob( [res.blob()], { type: "application/octet-stream"} );
})
}

Web Api Sample (can use this as reference for spring/grails. I am using grails)

File file = new File("path")
if(file.exists()){
    response.setContentType("application/octet-stream")
    response.setContentLength((int) file.length())
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"")
    response.outputStream << file.bytes
    response.outputStream.flush()
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s