Send FormData with other field in AngularJS

前端 未结 5 1075
天涯浪人
天涯浪人 2020-11-28 09:46

I have a form with two input text and one upload. I have to send it to the server but I have some problem concatenating the file with the text. The

5条回答
  •  攒了一身酷
    2020-11-28 10:20

    Here is the complete solution

    html code,

    create the text anf file upload fields as shown below

        

    directive code

    create a filemodel directive to parse file

    .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(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };}]);
    

    Service code

    append the file and fields to form data and do $http.post as shown below remember to keep 'Content-Type': undefined

     .service('fileUploadService', ['$http', function ($http) {
        this.uploadFileToUrl = function(file, username, password, dob, email, uploadUrl){
            var myFormData = new FormData();
    
            myFormData.append('file', file);
            myFormData.append('username', username);
            myFormData.append('password', password);
            myFormData.append('dob', dob);
            myFormData.append('email', email);
    
    
            $http.post(uploadUrl, myFormData, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            })
                .success(function(){
    
                })
                .error(function(){
                });
        }
    }]);
    

    In controller

    Now in controller call the service by sending required data to be appended in parameters,

    $scope.saveData  = function(model){
        var file = model.myFile;
        var uploadUrl = "/api/createUsers";
        fileUpload.uploadFileToUrl(file, model.username, model.password, model.dob, model.email, uploadUrl);
    };
    

提交回复
热议问题