title: Download file from an ASP.NET Web API method using AngularJS
body: <p>In my Angular JS project, I've an <code>&lt;a&gt;</code> anchor tag, which when clicked makes an HTTP <code>GET</code> request to a WebAPI method that returns a file. </p>
  
  <p>Now, I want the file to be downloaded to the user once the request is successful. How do I do that?</p>
  
  <p>The anchor tag: </p>
  
  <pre><code>&lt;a href="#" ng-click="getthefile()"&gt;Download img&lt;/a&gt;
  </code></pre>
  
  <p>AngularJS:</p>
  
  <pre><code>$scope.getthefile = function () {        
      $http({
          method: 'GET',
          cache: false,
          url: $scope.appPath + 'CourseRegConfirm/getfile',            
          headers: {
              'Content-Type': 'application/json; charset=utf-8'
          }
      }).success(function (data, status) {
          console.log(data); // Displays text data if the file is a text file, binary if it's an image            
          // What should I write here to download the file I receive from the WebAPI method?
      }).error(function (data, status) {
          // ...
      });
  }
  </code></pre>
  
  <p>My WebAPI method:</p>
  
  <pre class="lang-cs prettyprint-override"><code>[Authorize]
  [Route("getfile")]
  public HttpResponseMessage GetTestFile()
  {
      HttpResponseMessage result = null;
      var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.jpg");
  
      if (!File.Exists(localFilePath))
      {
          result = Request.CreateResponse(HttpStatusCode.Gone);
      }
      else
      {
          // Serve the file to the client
          result = Request.CreateResponse(HttpStatusCode.OK);
          result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
          result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
          result.Content.Headers.ContentDisposition.FileName = "SampleImg";                
      }
  
      return result;
  }
  </code></pre>