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

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

本文介绍了如何在MVC中使用AngularJS上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我创建了一个 javascript 文件,其中包含 -

这里是 serviceJS-

 var app = angular.module("app", []);app.service('FileUploadService', ['$http', function ($http) {this.uploadFileToUrl = 函数(文件,uploadUrl){var fd = new FormData();fd.append('文件', 文件);$http.post(uploadUrl, fd, {变换请求:angular.identity,标头:{'内容类型':未定义}}).成功(功能(){}).错误(函数(){});}}]);

这是控制器部分-

 app.controller('FileUploadController', ['$scope', 'FileUploadService', function($scope, FileUploadService) {$scope.uploadFile = 函数 () {var 文件 = $scope.myFile;console.log('文件是');控制台目录(文件);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()">上传</button>

它在控制器中将 myFile 视为未定义.我无法调试这个.
提前致谢.

解决方案

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

angular.module("app.directives", []).directive('fileUpload', function () {返回 {范围:真实,链接:功能(范围,EL,属性){el.bind('change', function (event) {var 文件 = event.target.files;//迭代文件,因为可以在元素上指定multiple"如果(文件.长度== 0){scope.$emit("fileSelected", { file: null, field: event.target.name });} 别的{for (var i = 0;i<files.length;i++) {//向上发射事件scope.$emit("fileSelected", { file: files[i], field: event.target.name });}}});}};});

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

$scope.$on("fileSelected", function (event, args) {$scope.$apply(function () {开关(args.field){案例我的文件":$scope.myFile = args.file;休息;默认:休息;}});});

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

this.uploadFileToUrl = 函数(文件,uploadUrl){返回 $http({方法:'POST',网址:上传网址,标头:{'内容类型':未定义},变换请求:函数(){var formData = new FormData();如果(文件){formData.append("myFile", 文件);}返回表单数据;}})}

As I am new to AngularJS, I Don't know how to upload file in MVC using AngularJS.I am trying to upload some files without any specific type or extension, but failed.

I created a javascript file which have-

Here is 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 () {
            });
        }
    }]);

This is controller part-

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

And, In view page,

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

It is taking myFile as undefined in controller. I am unable to debug this.
Thanks in advance.

解决方案

You cannot bind the <input type="file"> to a $scope variable. You will need to create a directive which captures the onchange event of the file input tag. For example <input type="file" name="myFile" file-upload/> and the directive looks like this:

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

After that, you can catch the broadcast in your controller like this:

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

Your Service method can be comething like this:

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

这篇关于如何在MVC中使用AngularJS上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:12