使用 Angular/C 上传文件#

Uploading files using Angular/C#

我有一个内置客户端 Angular。我正在尝试上传要由 asp.net 服务器端代码处理的文件。虽然我已经设法在文件控件中获取文件,但我不知道如何将二进制数据传递到服务器端。我的客户端代码如下所示

HTML代码

<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>

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);
                });

        };

    }; 

我想从中访问上传文件的服务器端代码

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

    }

当我 运行 代码时,我会收到每个上传文件的警报。然后代码进入服务器端如下图所示

我想从这里访问文件。我在网上看到他们显示 Request.Files 显示正在上传的文件集合,但是当我尝试这样做时,编译器开始抱怨。

任何人都知道在这种情况下我应该如何传递从客户端上传的二进制数据并从服务器端访问它

在angular中调用服务器端时可以使用$upload来上传文件这里是一个例子:

 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;
    }

如果需要,上述函数将传递文件和额外的参数。

服务器端

    [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;
    }