Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

javascript - How to Upload file using AngularJS in MVC

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...