AngularJS загружает картинки с формданными

Я пытаюсь опубликовать изображение как часть formData в своем клиентском интерфейсе API, учитывая, что API позволяет мне отправлять файлы только как часть данных формы без URL-адреса для загрузки физического файла. Ниже приведен код, который я использую до сих пор, я также попробовал некоторые модули загрузки Angular ex. Угловая загрузка файла, но я ничего не могу найти, чтобы помочь мне опубликовать файл как часть данных формы (multipart/ form data), так как все ожидают, что URL загрузит физический файл. Может кто-нибудь помочь мне, пожалуйста, найдите способ опубликовать изображения / файлы в виде данных формы ИЛИ скажите мне, что именно я делаю неправильно в моем коде ниже? Спасибо

Метод обслуживания, используемый при публикации:

       var deferred = $q.defer();
       $http({ method:'POST',
               url:'http://localhost/api/clients.php',
               data: {
                    action: 'updateClient',
                    img: pictureFile
               },
               transformRequest: angular.identity,
               headers: {  'Content-Type': 'multipart/form-data',
                           'Token': '1234567890'
                        }
             }).success(function(data,status,headers,config){
                 deferred.resolve(data);
             }).error(function(data,status,headers,config){ 
                deferred.reject(status);
             });

       return deferred.promise   

form.html

<form name="clientForm">
 <fieldset>
   <input id="name" type="text" placeholder="Name" ng-model="client.name">
   <input type="file" file-model="pictureFile"/>
 </fieldset>
 <button type="submit" ng-click="updateClient(client, pictureFile)">Submit</button>
</form>

директива

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

1 ответ

Решение

angular-file-upload позволяет отправлять данные формы / области + файл (ы). Приведенный ниже код взят из их документации, обратите внимание на параметры "data" и "file", используемые в методе $upload.upload()

    //inject angular file upload directives and service.
    angular.module('myApp', ['angularFileUpload']);

    var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
      $scope.onFileSelect = function($files) {
        //$files: an array of files selected, each file has name, size, and type.
        for (var i = 0; i < $files.length; i++) {
          var file = $files[i];
          $scope.upload = $upload.upload({
            url: 'server/upload/url', //upload.php script, node.js route, or servlet url
            // method: POST or PUT,
            // headers: {'header-key': 'header-value'},
            // withCredentials: true,
            data: {myObj: $scope.myModelObj},
            file: file, // or list of files: $files for html5 only
            /* set the file formData name ('Content-Desposition'). Default is 'file' */
            //fileFormDataName: myFile, //or a list of names for multiple files (html5).
            /* customize how data is added to formData. See #40#issuecomment-28612000 for sample code */
            //formDataAppender: function(formData, key, val){}
          }).progress(function(evt) {
            console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
          }).success(function(data, status, headers, config) {
            // file is uploaded successfully
            console.log(data);
          });
          //.error(...)
          //.then(success, error, progress); 
          //.xhr(function(xhr){xhr.upload.addEventListener(...)})// access and attach any event listener to XMLHttpRequest.
        }
        /* alternative way of uploading, send the file binary with the file's content-type.
           Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed. 
           It could also be used to monitor the progress of a normal http post/put request with large data*/
        // $scope.upload = $upload.http({...})  see 88#issuecomment-31366487 for sample code.
      };
    }];
Другие вопросы по тегам