Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
we will get the file content (byte array) , its MIME_Type and file name with extension from the API call to the success of hhtp request in angularjs controller now my task is to download it as a file in the browser as normal file download that we see regularly (using angularJS or javascript or jquery).

it should work in IE and chrome for sure.

Please help me.







Code in API controller
----------------------------------------------

// gets file data from Db based on file Id
[HttpGet]
public AttachedFile GetFileData(int fileId)
{
try
{
// id =1010
var fileData = _fileUploadManager.GetFileData(1010);

if (fileData != null)
{
return fileData;

}
else
{
return null;
}
}
catch (Exception ex)
{

throw ex;
}
}


---------------------------------


public class AttachedFile
{

public int fieldId;

public string fileName; // it includes extension of file too

public byte[] fileContent;

//public DateTime createdOn;

}



client side Code :
---------------------------------

// the below code is using in angularJS controller

---------------------------------

var getFileDownloadData = function ( inputParams) { // here inputParams is 1010 which is passed as id to controller API)

$http.get('http://sampleproject/api/FileUpload/', {
params: { '': inputParams }
})
.success(function (data) {
// debugger;
if (data != null) {

// in this data i have the information of file name, extension and fileContent which is byteArray.

// do something to download the file to browser.


}

}).error(function (msg, code) {
console.log(msg+'_'+code);
});

};
-----------------------------------






any kind of help would be appreciated.
thanks in Advance.

Posted
Updated 28-Apr-15 3:15am
v4
Comments
[no name] 28-Apr-15 8:47am    
Will you please share some code block to understand your requirement?
Rohith Reddy Vadiyala 28-Apr-15 9:14am    
I have shared the code that I started with.
any kind of help would be appreciated.
thanks in Advance.

I guess the below URL will resolve your issue.

http://stackoverflow.com/questions/24080018/download-file-from-a-asp-net-web-api-method-using-angularjs
 
Share this answer
 
Comments
Rohith Reddy Vadiyala 30-Apr-15 1:58am    
do you have any sample data which is a response to success method??
Actually the problem is I could able to download a file (pdf) but while opening it throws error in adobe reader: - "there was an error opening this document. the root object is missing or invalid"
XML
<!DOCTYPE html>
<html>

<head>
  <title>Using $http.get to read binary data</title>
</head>

<body ng-app>
  <h1>Using $http.get to read binary data</h1>
  <div ng-controller="FetchCtrl">
    Image loaded using the <tt>src</tt> attribute of an <tt>&lt;img&gt;</tt> element:
    <div>
      <img ng-src="{{URL}}" />
    </div>
    Click the following button to fetch the same image dynamically:
    <br/>
    <button ng-click="fetch()">fetch</button>
    <br/>{{info}}
  </div>
  <script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
  <script>
    // Controller
    function FetchCtrl($scope, $http) {
      $scope.URL = "http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png";
      $scope.ORIGINAL_SIZE = 473831;
      $scope.info = "";

      $scope.fetch = function() {
        // Resetting headers to Accept */* is necessary to perform a simple cross-site request
        // (see https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Simple_requests)
        delete $http.defaults.headers.common['X-Requested-With'];
        $http.get($scope.URL, {
          responseType: "arraybuffer"
        }).
        success(function(data) {
          $scope.info =
            "Read '" + $scope.URL + "' with " + data.byteLength + " bytes in a variable of type '" + typeof(data) + "'. The original file has " + $scope.ORIGINAL_SIZE + " bytes."

// to download in IE >10 versions
          // Try using msSaveBlob if supported
          console.log("Trying saveBlob method ...");
          var blob = new Blob([data], {
            type: 'image/png'
          });
          console.log(blob);
          if (navigator.msSaveBlob)
            navigator.msSaveBlob(blob, 'Lenna.png');
          else {
            // Try using other saveBlob implementations, if available
            var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
            if (saveBlob === undefined) throw "Not supported";
            saveBlob(blob, filename);
          }
          console.log("saveBlob succeeded");


        }).
        error(function(data, status) {
          $scope.info = "Request failed with status: " + status;
        });
      };
    }
  </script>
</body>

</html>




References:

http://plnkr.co/edit/wjeBsrOgL9KrctmeVedM?p=preview

http://stackoverflow.com/questions/24080018/download-file-from-a-asp-net-web-api-method-using-angularjs
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900