How to upload a file using AngularJS and call the MVC API?

I am using AngularJS and I have an MVC 4 API that returns an 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 downloads the file nicely ... but I have not found a way to do this in Angular "... any help would be appreciated.

// _ e

+49
angularjs
Jan 08 '13 at 12:32
source share
10 answers

I had the same problem. Solved it using a javascript library called FileSaver

Just call

 saveAs(file, 'filename'); 

Full HTTP request:

 $http.post('apiUrl', myObject, { responseType: 'arraybuffer' }) .success(function(data) { var file = new Blob([data], { type: 'application/pdf' }); saveAs(file, 'filename.pdf'); }); 
+68
May 15 '14 at 16:22
source share
β€” -

Here you have the angularjs http request for an API that any client should do. Just adapt the URLs and WS parameters (if any) to your case. This is the mix between Naoe's answer and this :

 $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 }); 

Code Explanation:

  1. Angularjs requests the .pdf file at the URL: /path/to/your/API .
  2. Success received by reply
  3. We do the trick using JavaScript on the front-end:
    • Create the html ta: <a> link.
    • Click the <a> tag of the hyperlink using the JS click() function
  4. Remove the HTML <a> tag after clicking it.
+52
Dec 12 '14 at 11:41
source share

for different messages ... you cannot start the download via XHR. I needed to fulfill the condition for loading, so My solution was:

 //make the call to the api with the ID to validate someResource.get( { id: someId }, function(data) { //confirm that the ID is validated if (data.isIdConfirmed) { //get the token from the validation and issue another call //to trigger the download window.open('someapi/print/:someId?token='+ data.token); } }); 

I want that one way or another, or someday, the download can be started using XHR to avoid a second call .//_ e

+10
Jan 15 '13 at 14:56
source share

There are two ways to do this in angularjs ..

1) Direct redirection to your service call.

 <a href="some/path/to/the/file">clickme</a> 

2) By submitting a hidden form.

 $scope.saveAsPDF = function() { var form = document.createElement("form"); form.setAttribute("action", "some/path/to/the/file"); form.setAttribute("method", "get"); form.setAttribute("target", "_blank"); var hiddenEle1 = document.createElement("input"); hiddenEle1.setAttribute("type", "hidden"); hiddenEle1.setAttribute("name", "some"); hiddenEle1.setAttribute("value", value); form.append(hiddenEle1 ); form.submit(); } 

use a hidden element when you need to send some element

 <button ng-click="saveAsPDF()">Save As PDF</button> 
+8
Nov 10 '14 at 9:54
source share

The horror solution worked well for me. However, the file was also not saved in Internet Explorer 10+. The following code worked for me for IE browser.

 var file = new Blob(([data]), { type: 'application/pdf' }); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(file, 'fileName.pdf'); } 
+3
Nov 20 '15 at 3:48
source share

Another example using Blob() code:

 function save(url, params, fileName){ $http.get(url, {params: params}).success(function(exporter) { var blob = new Blob([exporter], {type: "text/plain;charset=utf-8;"}); saveAs(blob, fileName); }).error(function(err) { console.log('err', err); }); }; // Save as Code function saveAs(blob, fileName){ var url = window.URL.createObjectURL(blob); var doc = document.createElement("a"); doc.href = url; doc.download = fileName; doc.click(); window.URL.revokeObjectURL(url); } 
+2
Jun 01 '16 at 21:49
source share

This is how I solved this problem

 $scope.downloadPDF = function () { var link = document.createElement("a"); link.setAttribute("href", "path_to_pdf_file/pdf_filename.pdf"); link.setAttribute("download", "download_name.pdf"); document.body.appendChild(link); // Required for FF link.click(); // This will download the data file named "download_name.pdf" } 
+1
Sep 05 '16 at 13:45
source share
 string trackPathTemp = track.trackPath; //The File Path var videoFilePath = HttpContext.Current.Server.MapPath("~/" + trackPathTemp); var stream = new FileStream(videoFilePath, FileMode.Open, FileAccess.Read); var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4"); result.Content.Headers.ContentRange = new ContentRangeHeaderValue(0, stream.Length); // result.Content.Headers.Add("filename", "Video.mp4"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Video.mp4" }; return result; 
0
Apr 01 '14 at 10:39 on
source share

using FileSaver.js solved my problem thanks to help, below code helped me

 '$' DownloadClaimForm: function (claim) { url = baseAddress + "DownLoadFile"; return $http.post(baseAddress + "DownLoadFile", claim, {responseType: 'arraybuffer' }) .success(function (data) { var file = new Blob([data], { type: 'application/pdf' }); saveAs(file, 'Claims.pdf'); }); } 
0
Sep 29 '16 at 9:37
source share

It says Angular service. Angular file server uses FileSaver.js and Blob.js.

  vm.download = function(text) { var data = new Blob([text], { type: 'text/plain;charset=utf-8' }); FileSaver.saveAs(data, 'text.txt'); }; 
0
Jan 16 '18 at 14:44
source share



All Articles