I am using AngularJS, and I have a MVC 4 API that returns a HttpResponseMessage with an attachment.
var result = new MemoryStream(pdfStream, 0, pdfStream.Length) { Position = 0 }; var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StreamContent(result) }; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "MyPdf.pdf" }; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return response;
I am using a jQuery plugin called fileDownload... which download the file beautifully... but I havent found the way to do this in the "Angular" way... any help will be appreciated.
// _e
It first loops through the Request. Files collections and then inside the loop, each file is saved in the folder named Uploads. Finally a success response is sent back to the AngularJS client. The View consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
To download AngularJS library, go to angularjs.org -> click download button, which will open the following popup. Select the required version from the popup and click on download button in the popup.
AngularJS with Visual Studio Click on ASP.NET Web Application, rename the application and hit “ok” button at bottom right. Choose empty template in next window and click on “ok” button. It will take a while to load a sample empty project. Now the first thing we need to do is register AngularJS.
I had the same problem. Solved it by using a javascript library called FileSaver
Just call
saveAs(file, 'filename');
Full http post request:
$http.post('apiUrl', myObject, { responseType: 'arraybuffer' }) .success(function(data) { var file = new Blob([data], { type: 'application/pdf' }); saveAs(file, 'filename.pdf'); });
Here you have the angularjs http request to the API that any client will have to do. Just adapt the WS url and params (if you have) to your case. It's a mixture between Naoe's answer and this one:
$http({ url: '/path/to/your/API', method: 'POST', params: {}, headers: { 'Content-type': 'application/pdf', }, responseType: 'arraybuffer' }).success(function (data, status, headers, config) { // TODO when WS success var file = new Blob([data], { type: 'application/csv' }); //trick to download store a file having its URL var fileURL = URL.createObjectURL(file); var a = document.createElement('a'); a.href = fileURL; a.target = '_blank'; a.download = 'yourfilename.pdf'; document.body.appendChild(a); //create the link "a" a.click(); //click the link "a" document.body.removeChild(a); //remove the link "a" }).error(function (data, status, headers, config) { //TODO when WS error });
Explanation of the code:
/path/to/your/API
.<a>
.<a>
tag, using the JS click()
function<a>
tag, after its click.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With