Download a file with angularJS and c #

0

I have a question. I need to know how to download a file with angularJS and C # MVC . I already managed to save the file in a separate route, but when downloading I do not know how to recover it. I understand that it is by method GET .

This is how I am sending the file:

var config = {

  headers: {
    'Content-Type': undefined
  },
  transformRequest: function(data) {
    var formData = new FormData();

    formData.append("jsonData", angular.toJson(data.jsonData));

    for (var i = 0; i < data.files.length; i++) {
      formData.append("file" + i, data.files[i]);
    }

    return formData;
  }
};

var datos = {
  jsonData: solicitud,
  files: archivo
};

$http.post('./GuardarSolicitudConArchivo', datos, config).then(successCallback, errorCallback);
    
asked by Camilo López 04.04.2018 в 22:45
source

2 answers

1

To download a file you will have to use Blob of javascript

AngularJS: Download Files by Sending to HTTP Request to Web API

As you will see in the code example, the magic is given in these lines

var linkElement = document.createElement('a');

try {

    var blob = new Blob([data], { type: contentType });
    var url = window.URL.createObjectURL(blob);

    linkElement.setAttribute('href', url);
    linkElement.setAttribute("download", filename);

    var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
    });

    linkElement.dispatchEvent(clickEvent);

} catch (ex) {
    console.log(ex);
}

the stream that the webapi sends, or action, in the response will be used by the blob so that later the download can be forced.

    
answered by 04.04.2018 / 22:56
source
1

You can use a JavaScript library called FileSaver

Just call

saveAs(archivo, 'NombreArchivo');

Full http request:

$http.post('apiUrl', myObject, { responseType: 'arraybuffer' })
  .success(function(data) {
            var archivo= new Blob([data], { type: 'application/pdf' });
            saveAs(archivo, 'NombreArchivo.pdf');
        });
  

myObject is the POST information you are sending to your API, f.ex. an order to be presented as pdf

Another example:

Here is the angularjs http request to the API that any client will have to do.

$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);
    a.click();
}).error(function(data, status, headers, config) {

});

Explanation of the code:

  • Angularjs requests a PDF at the specified URL.
  • Success is received in the response.
  • We execute a trick with JavaScript in the front-end:

    • Create a tag <a> html
    • Click the% link% tag of the hyperlink, using the function <a> JS
  • Note: To remove the link after it has been added to the  body, simply replace the last 2 lines in your successful controller with this: click()

        
    answered by 04.04.2018 в 22:56