0

Im using the filesaver js library for download files... i'm generating a endpoint with web api that returns my file from base64 but i don't know how to return base64 as Blob for download with filesaver....

  • Im tried make differents responses types
  • try to understand how to does it works the Blob data
public HttpResponseMessage GetFile(int id)
{
   string mybase64file = GetBase64File(id)
   byte[] bytes = Convert.FromBase64String(mybase64file );

   MemoryStream ms = new MemoryStream(bytes);


  HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
  result.Content = new StreamContent(ms);
  result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
  result.Content.Headers.ContentDisposition.FileName = "someFileName.pdf";
  result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

   return result;
}

AngularJS service:

function download() {
  var deferred = $q.defer()
  $http.get('url', {
    headers: {
      'Content-type': 'application/octet-stream',
    }, 
    responseType: 'blob'
  })
    .success(function (response) {
      saveAs(response, 'someName.pdf') 
    })
    .error(function (err) {
      deferred.reject(err)
    })

  return deferred.promise
}

When the angularjs service recieve to response, im call the "saveAs" function, but this generate the next error:

"angular.min.js:118 TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided."

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Alonso Contreras
  • 605
  • 2
  • 12
  • 29
  • You will get better stack traces if you use `angular.js` instead of `angular.min.js`. – georgeawg Aug 30 '19 at 19:55
  • The `.success` method has been [removed from the AngularJS framework](https://stackoverflow.com/questions/35329384/why-are-angularjs-http-success-error-methods-deprecated-removed-from-v1-6/35331339#35331339). Avoid using the [deferred anti-pattern](https://stackoverflow.com/questions/30750207/is-this-a-deferred-antipattern). – georgeawg Aug 30 '19 at 19:57

1 Answers1

0

To return a file from ASP MVC CORE, use:

return File(stream, "application/octet-stream");
return FileStreamResult(stream, "application/octet-stream");
return PhysicalFileResult("path to file", "application/octet-stream");

With that, you dont even need filesaver js library, the file will download automatically once that link is requested.

One more thing: You cant download a file with Ajax (....$http.get('url', {....)!

You could use Fetch API do get the blob, see implementation here: https://stackoverflow.com/a/9970672/3563013

To address the specific error ( "angular.min.js:118 TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided." ), its possible window.URL.createObjectURL is not supported in the browser you are using to test.

McKabue
  • 2,076
  • 1
  • 19
  • 34