使用Angular / C#上传文件

时间:2015-01-08 16:12:02

标签: c# asp.net angularjs upload

我有一个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()
    {

    }

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

Server side code

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

Compiler error when using Request.Files

在这种情况下,任何人都有关于如何能够传递从客户端上传的二进制数据并从服务器端访问它的任何线索

1 个答案:

答案 0 :(得分:2)

当您调用服务器端时,您可以使用$ 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;
    }

如果需要,上面的函数会传递文件和额外的args。

服务器端

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