一尘不染

如何在MVC中使用AngularJS上传文件

angularjs

由于我是AngularJS的新手,所以我不知道如何使用AngularJS在MVC中上传文件。我正在尝试上传一些没有任何特定类型或扩展名的文件,但失败了。

我创建了一个JavaScript文件,该文件具有-

这是serviceJS-

    var app = angular.module("app", []);        
    app.service('FileUploadService', ['$http', function ($http) {      
            this.uploadFileToUrl = function (file,  uploadUrl) {    
            var fd = new FormData();   
            fd.append('file', file);   
            $http.post(uploadUrl, fd, {   
                transformRequest: angular.identity,   
                headers: { 'Content-Type': undefined }   
            })   
            .success(function () {   
            })    
            .error(function () {    
            });     
        }   
    }]);

这是控制器部分-

    app.controller('FileUploadController', ['$scope', 'FileUploadService', function($scope, FileUploadService) { 
            $scope.uploadFile = function () {
            var file = $scope.myFile;
            console.log('file is ');
            console.dir(file);
            var uploadUrl = "/Home/FileUploadFromAngular";
            FileUploadService.uploadFileToUrl(file, uploadUrl);
        };
    }]);

并且,在查看页面中,

 <script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/AngScript/FileUpload.js"></script>
<script src="~/Scripts/angular-ui/ui-bootstrap.min.js"></script>
    <div ng-controller="FileUploadController">
        <input type="file" ng-model="myFile" />
        <button ng-click="uploadFile()">Upload</button>
    </div>

它在控制器中将 myFile 设为未定义。我无法调试。
提前致谢。


阅读 219

收藏
2020-07-04

共1个答案

一尘不染

您不能将绑定<input type="file">$scope变量。您将需要创建一个指令来捕获onchange event文件输入标签的。例如<input type="file" name="myFile" file-upload/>,伪指令如下所示:

angular.module("app.directives", []).directive('fileUpload', function () {
return {
    scope: true,
    link: function (scope, el, attrs) {
        el.bind('change', function (event) {
            var files = event.target.files;
            //iterate files since 'multiple' may be specified on the element
            if(files.length == 0){
                scope.$emit("fileSelected", { file: null, field: event.target.name });
            } else{
                for (var i = 0;i<files.length;i++) {
                    //emit event upward
                    scope.$emit("fileSelected", { file: files[i], field: event.target.name });
                }
            }
        });
    }
};
});

之后,您可以像这样在控制器中捕获广播:

$scope.$on("fileSelected", function (event, args) {
    $scope.$apply(function () {
        switch (args.field) {
            case "myFile":
                $scope.myFile = args.file;
                break;
            default:
                break;
        }
    });
});

您的服务方法可以是这样的:

this.uploadFileToUrl = function (file,  uploadUrl) { 
    return $http({
        method: 'POST',
        url: uploadUrl,
        headers: { 'Content-Type': undefined },
        transformRequest: function() {
            var formData = new FormData();
            if(file){
               formData.append("myFile", file); 
            }
            return formData;
        }
    })
}
2020-07-04