2

I have a client built in Angular. I am trying to upload files that are to be processed by the asp.net server side code. Although I have managed to get files in the file control but I don't know how I can pass the binary data to server side. My client side code looks as follows

HTML Code

<div>
<form name="form1" method="POST" enctype="multipart/form-data">
    <div>
        {{repopulatecftcModel.title}}
    </div>
    <div style="padding-top:15px;padding-bottom:15px;"><b>Toolkit - Repopulate Cftc Data</b></div>
    <div>
        <input type="file" id="updCftcFileUploader" name="files[]" multiple />
    </div>
    <div>
        <input type="button" value="Upload Files" title="Upload Files" ng-click="UploadCFTCFiles()" />
    </div>
    <div>
        <label ng-model="repopulatecftc.validationtext"></label>
    </div>
    <div>
        {{repopulatecftcModel.validationtext}}
    </div>
</form>

Controller Code in Angular

function controller($scope, $http, AppModel, WebFunctionService) {

        $scope.UploadFiles = function (evt) {

            var files = document.getElementById('updFileUploader').files;
            for(var i = 0; i < files.length; i++) {
                var file = files[i];
                if (file) {
                    //  getAsText(file);
                    alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);
                }
            }
            var parameters = { directory: $scope.defaultsSaveDirectory, filename: "" };
            WebFunctionService.promiseWebMethod('UploadFiles', angular.fromJson(parameters), true)
                .success(function () {
                    $scope.userMessage = "File(s) successfully uploaded";
                    console.log($scope.userMessage);
                })
                .error(function (error) {
                    $scope.userMessage = "ERROR uploading files" + error;
                    console.log($scope.userMessage);
                });

        };

    }; 

Server side code where I want to access the uploaded files from

[Route("UploadFiles")]
    [HttpPost]
    public void UploadFiles()
    {

    }

When I run the code I do get alerts for each of the file being uploaded. Then the code get into the server side as shown in the image below

Server side code

Its here that I want to access the files from. I have seen in the web where they show Request.Files shows the collection of files being uploaded but when I try to do that the compiler starts complaining.

Compiler error when using Request.Files

Anyone have any clues as to how I should be able to pass binary data being uploaded from client side in this case and access it from the server side

1 Answer 1

3

In angular when you call the server side you can use $upload to upload a file here is an example:

 var uploadFile = function (file, args) {
        var deferred = $q.defer();
        $upload.upload({
            url: "<your url goes here>",
            method: "POST",
            file: file,
            data: args
        }).progress(function (evt) {
            // get upload percentage
            console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
        }).success(function (data, status, headers, config) {
            // file is uploaded successfully
            deferred.resolve(data);
        }).error(function (data, status, headers, config) {
            // file failed to upload
            deferred.reject();
        });

        return deferred.promise;
    }

The above function will pass the file along with extra args if you need it.

Server side

    [HttpPost]
    public async Task<HttpResponseMessage> AddFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
        var provider = new MultipartFormDataStreamProvider(root);
        var result = await Request.Content.ReadAsMultipartAsync(provider);

        // On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
        // so this is how you can get the original file name
        var originalFileName = GetDeserializedFileName(result.FileData.First());

        var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
        string path = result.FileData.First().LocalFileName;

        //Do whatever you want to do with your file here

        return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName );
    }

    private string GetDeserializedFileName(MultipartFileData fileData)
    {
        var fileName = GetFileName(fileData);
        return JsonConvert.DeserializeObject(fileName).ToString();
    }

    public string GetFileName(MultipartFileData fileData)
    {
        return fileData.Headers.ContentDisposition.FileName;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

It did answer my original question in terms of passing file from angular client to server side code so marked it as correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.