Angular文件上传到PHP后端

时间:2016-12-29 21:41:44

标签: javascript php angularjs xmlhttprequest angular-http

我是开发人员,我尝试学习一些AngularJs,现在我尝试做一个表单,并且必须从input [file]发送一个文件到php,但当我点击buttom时,文件没有被发送到这个php,尝试一些例子,但都没有用。

此致!!

我的代码:

<form>
    <input type="file" file-model="csvFile" name="contactFile" on-read-file="showContent($fileContent)" class="filestyle glyfecha glyphicon input-sm" />
    <button type="submit" class="btn btn-success btn-block" ng-click="sendForm()" style="margin-top: 10px;margin-bottom: 10px;">Guardar contactos</button>
</form>


app.directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                console.log(element[0].files[0]);     //this work
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};
}]);

app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file){
    var fd = new FormData();
    fd.append('file', file);
    $http.post('v1/contact/upload/0', fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .then(function(response){
        console.log(response.data);
    })
}
}]);

app.controller('addcontacto', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.sendForm = function() {
    var file = $scope.csvFile;
    fileUpload.uploadFileToUrl(file);
};
}]);

0 个答案:

没有答案