File Upload using AngularJS

前端 未结 29 2027
野趣味
野趣味 2020-11-21 07:24

Here is my HTML form:

相关标签:
29条回答
  • 2020-11-21 08:12

    HTML

    <input type="file" id="file" name='file' onchange="angular.element(this).scope().profileimage(this)" />
    

    add 'profileimage()' method to your controller

        $scope.profileimage = function(selectimage) {
          console.log(selectimage.files[0]);
     var selectfile=selectimage.files[0];
            r = new FileReader();
            r.onloadend = function (e) {
                debugger;
                var data = e.target.result;
    
            }
            r.readAsBinaryString(selectfile);
        }
    
    0 讨论(0)
  • 2020-11-21 08:12

    This should be an update/comment to @jquery-guru's answer but as I don't have enough rep it will go here. It fixes the errors that are now generated by the code.

    https://jsfiddle.net/vzhrqotw/

    The change is basically:

    FileUploadCtrl.$inject = ['$scope']
    function FileUploadCtrl(scope) {
    

    To:

    app.controller('FileUploadCtrl', function($scope)
    {
    

    Feel free to move to a more appropriate location if desired.

    0 讨论(0)
  • 2020-11-21 08:15

    This is the modern browser way, without 3rd party libraries. Works on all the latest browsers.

     app.directive('myDirective', function (httpPostFactory) {
        return {
            restrict: 'A',
            scope: true,
            link: function (scope, element, attr) {
    
                element.bind('change', function () {
                    var formData = new FormData();
                    formData.append('file', element[0].files[0]);
                    httpPostFactory('upload_image.php', formData, function (callback) {
                       // recieve image name to use in a ng-src 
                        console.log(callback);
                    });
                });
    
            }
        };
    });
    
    app.factory('httpPostFactory', function ($http) {
        return function (file, data, callback) {
            $http({
                url: file,
                method: "POST",
                data: data,
                headers: {'Content-Type': undefined}
            }).success(function (response) {
                callback(response);
            });
        };
    });
    

    HTML:

    <input data-my-Directive type="file" name="file">
    

    PHP:

    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
    
    // uploads image in the folder images
        $temp = explode(".", $_FILES["file"]["name"]);
        $newfilename = substr(md5(time()), 0, 10) . '.' . end($temp);
        move_uploaded_file($_FILES['file']['tmp_name'], 'images/' . $newfilename);
    
    // give callback to your angular code with the image src name
        echo json_encode($newfilename);
    }
    

    js fiddle (only front-end) https://jsfiddle.net/vince123/8d18tsey/31/

    0 讨论(0)
  • 2020-11-21 08:15

    HTML

    <html>
        <head></head>
    
    <body ng-app = "myApp">
    
      <form ng-controller = "myCtrl">
         <input type = "file" file-model="files" multiple/>
         <button ng-click = "uploadFile()">upload me</button>
         <li ng-repeat="file in files">{{file.name}}</li>
      </form>
    

    Scripts

      <script src = 
         "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
      <script>
        angular.module('myApp', []).directive('fileModel', ['$parse', function ($parse) {
            return {
               restrict: 'A',
               link: function(scope, element, attrs) {
                  element.bind('change', function(){
                  $parse(attrs.fileModel).assign(scope,element[0].files)
                     scope.$apply();
                  });
               }
            };
         }]).controller('myCtrl', ['$scope', '$http', function($scope, $http){
    
    
           $scope.uploadFile=function(){
           var fd=new FormData();
            console.log($scope.files);
            angular.forEach($scope.files,function(file){
            fd.append('file',file);
            });
           $http.post('http://localhost:1337/mediaobject/upload',fd,
               {
                   transformRequest: angular.identity,
                   headers: {'Content-Type': undefined}                     
                }).success(function(d)
                    {
                        console.log(d);
                    })         
           }
         }]);
    
      </script>
    

    0 讨论(0)
  • 2020-11-21 08:15

    Easy with a directive

    Html:

    <input type="file" file-upload multiple/>
    

    JS:

    app.directive('fileUpload', function () {
    return {
        scope: true,        //create a new scope
        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
                for (var i = 0;i<files.length;i++) {
                    //emit event upward
                    scope.$emit("fileSelected", { file: files[i] });
                }                                       
            });
        }
    };
    

    In the directive we ensure a new scope is created and then listen for changes made to the file input element. When changes are detected with emit an event to all ancestor scopes (upward) with the file object as a parameter.

    In your controller:

    $scope.files = [];
    
    //listen for the file selected event
    $scope.$on("fileSelected", function (event, args) {
        $scope.$apply(function () {            
            //add the file object to the scope's files collection
            $scope.files.push(args.file);
        });
    });
    

    Then in your ajax call:

    data: { model: $scope.model, files: $scope.files }
    

    http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/

    0 讨论(0)
  • 2020-11-21 08:15

    I know this is a late entry but I have created a simple upload directive. Which you can get working in no time!

    <input type="file" multiple ng-simple-upload web-api-url="/api/Upload" callback-fn="myCallback" />
    

    ng-simple-upload more on Github with an example using Web API.

    0 讨论(0)
提交回复
热议问题