如何在AngularJS中上传多部分表单? [英] How do I upload a multipart form in AngularJS?

查看:98
本文介绍了如何在AngularJS中上传多部分表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

表单视图:

        <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 in my services:

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

我没有包含控制器代码,因为它只是从中继表单数据服务的模式和该部分的工作。

I've not included the controller code as it's just relaying the form data from the modal to the service and that part's working.

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

The problem I'm having is that the file is being submitted as encoded data (my knowledge is a bit shaky about binary data and blobs etc). And my API (written in Symfony2) is expecting a normal file submission as opposed to the data string.

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

So how would I convert that binary blob into an image file I can then submit? Or am I missing something?

推荐答案

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

use this module https://github.com/danialfarid/angular-file-upload is very simple to use.

ex :

    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

HTML CODE

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

这篇关于如何在AngularJS中上传多部分表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆