Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to download file using AngularJS and calling MVC API?

Tags:

angularjs

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

like image 693
Edwin Beltran Avatar asked Jan 08 '13 12:01

Edwin Beltran


People also ask

How upload file with AngularJS and ASP NET MVC application?

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.

How do I download a script in AngularJS?

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.

Can we use AngularJS with ASP NET MVC?

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.


2 Answers

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');         }); 
like image 107
Naoe Avatar answered Oct 04 '22 04:10

Naoe


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:

  1. Angularjs request a file.pdf at the URL: /path/to/your/API.
  2. Success is received on the response
  3. We execute a trick with JavaScript on the front-end:
    • Create an html link ta: <a>.
    • Click the hyperlink <a> tag, using the JS click() function
  4. Remove the html <a> tag, after its click.
like image 36
tremendows Avatar answered Oct 04 '22 02:10

tremendows