简体   繁体   中英

Send an excel data to web api service from Angular UI

In my UI project , I have a file uploader control which looks like :

            <div class="col-lg-2 col-sm-2 col-md-2">
                <div style="font-size:14px; ">
                    <label>Upload File</label>
                    <div class="ui-select">
                        <!--<div file-select="file"></div>-->
                        <input type="file" name="files" ng-files="getTheFiles($files)" />
                    </div>

                </div>

            </div>

And the directive ngFiles looks like :

CaseModule.directive('ngFiles', ['$parse', function ($parse) {

    function fn_link(scope, element, attrs) {
        var onChange = $parse(attrs.ngFiles);
        element.on('change', function (event) {
            onChange(scope, { $files: event.target.files });
        });
    };

    return {
        link: fn_link
    }
}]);

So, in the controller code I read the uploaded files as

   //UPLOAD FILE CODE
    var formdata;
    $scope.getTheFiles = function ($files) {
        formdata = new FormData();
        angular.forEach($files, function (value, key) {
            formdata.append(key, value);
        });
    };

    // NOW UPLOAD THE FILES.
    $scope.uploadFiles = function () {
        var request = {
            method: 'POST',
            url: BasePath + 'caseNative/UploadFiles/',
            data: formdata,
            headers: {
                'Content-Type': undefined
            }
        };

Now I dont know how to send this excel data to the server . Could someone help me n this regard ? I want to be able to read the excel data .

Thanks in advance.

With Asp.Net WebApi MVC, create a controller such as FileUploadController .

Prefix a API route to the API you are using. HttpContext library that would read any files over the said API.

public class FileUploadController : ApiController
{
  [Route("caseNative/UploadFiles/")]
  [HttpPost]

  public HttpResponseMessage UploadFile()
  {
     HttpResponseMessage response = null;
     try
     {
        if (HttpContext.Current.Request.Files.AllKeys.Any()){
            //If any file exist, then it would be available in the key
            //you have appended while creating a formdata.
            var httpPostedUploadFile = HttpContext.Current.Request.Files["Key"];
        }
     }
     catch (Exception e)
     {
        throw ex;
     }
}

Above code works for single file upload, if the request contains more than one file, you could modify the code to loop around the files.

Further more, you could read the Documentation here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM