File Upload using AngularJS

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

Here is my HTML form:

29条回答
  •  悲&欢浪女
    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:

    
    

    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/

提交回复
热议问题