如何在AngularJS中上传多部分表单?

时间:2014-10-02 13:39:49

标签: javascript angularjs symfony binaryfiles

表单视图:

        <form enctype="multipart/form-data" ng-submit="upload(file)">

            <input type="file" ng-model="modal.file" accept="image/gif" app-filereader /><br />

            <br>

            <textarea name="description" placeholder="Description" ng-model="description" id="" cols="30" rows="10"></textarea>

            <br>

            <input type="hidden" name="user" ng-model="user" value="{{ user }}" />

            <br>

            <input type="submit" value="Submit" class="network-sensitive button button-block button" />

        </form>

指令:

.directive('appFilereader', function(
$q
){
    var slice = Array.prototype.slice;

return {
    restrict: 'A'
    , require: '?ngModel'
    , link: function(scope, element, attrs, ngModel){
        if(!ngModel) return;

        ngModel.$render = function(){}

        element.bind('change', function(e){
            var element = e.target;

            $q.all(slice.call(element.files, 0).map(readFile))
            .then(function(values){
                if(element.multiple) ngModel.$setViewValue(values);
                else ngModel.$setViewValue(values.length ? values[0] : null);
            });

            function readFile(file) {
                var deferred = $q.defer();

                var reader = new FileReader()
                reader.onload = function(e){
                    deferred.resolve(e.target.result);
                }
                reader.onerror = function(e) {
                    deferred.reject(e);
                }
                reader.readAsDataURL(file);

                return deferred.promise;
            }

        });

    }

};

});

我的服务中的上传功能:

upload: function(file) {
  var token = $window.sessionStorage.token;

  var url = 'http://url.co/api/posts/creates';

  var $cache = $cacheFactory.get('$http');

  var deffered = $q.defer();

  var data = $cache.get(url);

  if(!data) {
      $http({
        url: url, 
        method: "POST",
        params: { access_token: token },
        data: file,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
      }).then(function(res) {
      deffered.resolve(res);
    });
  } else {
    deffered.resolve(data);
  }

  return deffered.promise;
  }

我没有包含控制器代码,因为它只是将表单数据从模式转发到服务并且该部分正在工作。

我遇到的问题是文件是作为编码数据提交的(我的知识对于二进制数据和blob等有点不稳定)。我的API(用Symfony2编写)期望正常的文件提交而不是数据字符串。

那么我如何将该二进制blob转换为我可以提交的图像文件?或者我错过了什么?

2 个答案:

答案 0 :(得分:1)

使用此模块https://github.com/danialfarid/angular-file-upload 使用非常简单。

前:

    var $file;//single file 
    $scope.sendFiles= function(){
     $upload.upload({
                        url: yourUrl,
                        method: "POST",
                        data: { data: $scope.yourOtherObject },
                        file: $file
                    }).success(function (data, status, headers, config) {
                        // file is uploaded successfully
                        console.log(data);
                        console.log("File upload SUCCESS");
                    }).error(function (data, status) {
                       console.log("File upload FAILED");
                    });
    } 

    $scope.onFileSelect = function ($files) {
                for (var i = 0; i < $files.length; i++) {
                    $file = $files[i];//set a single file
                }
           };

HTML CODE

<input type="file" name="myfile" ng-file-select="onFileSelect($files)" />
<button ng-click='sendFiles()'>Send file</button>

答案 1 :(得分:0)

问题是$ http服务,默认情况下使用内容类型为 application / json ,在您的情况下,它必须是 application / x-www-form-urlencoded 要解决此问题,您可以使用以下指令:https://github.com/nervgh/angular-file-upload/wiki/Module-API,它还支持将数据与文件一起发送。

另一种方法是在你的指令中使用formData对象和XmlHttpRequest,如下所示:

                var data = new FormData();
                var xhr = new XMLHttpRequest();
                data.append('file', files[i], files[i].name);
                xhr.open('POST', scope.mseUploadFile);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var result = xhr.responseText;

                        if (scope.callback) {
                            scope.$apply(function () {
                                scope.callback({ $data: result });
                            });
                        }

                    }
                    else if (xhr.readyState == 4 && xhr.status == 400) {
                        scope.$apply(function () {
                            if (scope.onError) {
                                scope.onError({ $error: xhr.responseText });
                            }
                            handleError(xhr.responseText);
                        });

                    }
                };
                xhr.send(data);