使用jpeg / jpg作为blob填充ng-flow

时间:2015-01-31 17:24:06

标签: javascript angularjs blob angular-resource ng-flow

我目前正尝试使用来自我的网络服务器(nodejs http-server)的图像填充ng-flow,我找到了这个帖子:

Populating image files with ng-flow.js from json

正如您在Aidas的回答中所看到的,他说您需要将数据添加到blob然后使用addFile(blob)

但是...当我使用$ resource来获取一个网址时:

http://localhost:8080/3c6397ff-cbb4-4a1c-98b3-5304e02c1bd4.jpg

然后从$ resource获取值,并将其添加到blob中,图像丢失 - 在ng-flow中,它表示blob是15kb - 而实际图像不是700kb。

我已经知道图片可能是base64格式的,但我的谷歌开发控制台说:

content-length:780831
content-type:image/jpeg; charset=utf-8

如果我查看google dev控制台中的响应数据,那里会出现很多问号(我猜不会显示该字符)。

如何正确格式化响应,以便使用addFile(blob)函数将其添加到ng-flow?

3 个答案:

答案 0 :(得分:3)

我在Populating image files with ng-flow.js from json

中做了一些结合cvjensen解决方案和penner的方法

控制器:

首先我从db读取图像并将它们存储在$ scope.project.images:

$scope.project.images : [ 
        {
            "image_type" : "image/jpeg",
            "src" : "/images/uploaded/flow-122256-fontiosojpg.1",
            "alt" : "fontioso.jpg",
            "_id" : ObjectId("5608ef37f7672d8b1fcab111")
        }
    ]

然后:

Flow.prototype.addExistingFile = function (file, event) {
  var f = new Flow.FlowFile(this, file);
  this.files.push(f);
};

angular.forEach($scope.project.images, function(value, key) {
    getBase64Images.get(value.src) //src contains the full path to img
        .success(function(data) {
             var blob = new Blob([data.data], {type: value.image_type});
              blob.name = value.alt;
              blob.image_url = value.src;
              blob.alt_text = value.alt;
              $scope.uploader.flow.addExistingFile(blob);
        })
        .error(function(error){
            console.log(error);
    });

});

服务:

.factory("getBase64Images", ['$http', function ($http) {
    return {
        get: function (url) {
            return $http.get(
                url, { 
                responseType: 'arraybuffer',
                transformResponse: function(data) {
                  console.log(data);
                  return { data: data };
                }
            }
          );
        }
    };
  }]);

答案 1 :(得分:1)

我最终这样做..

我的$资源功能如下:

ENV.imagesEndpoint =' http://localhost:8080/

id =图片名称/ ID

getimages: $resource(ENV.imagesEndpoint + id, {}, {
    get: { 
      method: 'GET',  
      isArray: false,
      responseType: 'arraybuffer',
      transformResponse: function(data) {
        // Stores the ArrayBuffer object in a property called "data"
        return { data: data };
      }
      //headers: {'Content-Type': 'image/jpeg;charset=utf-8;base64'}
    }
  })

我的控制器看起来像:

angular.forEach($scope.images, function(imageid) {
        filefactory(imageid).getimages.get().$promise.then(function(value) {
          $timeout(function() {
              var blob = new Blob([value.data], {type: 'image/jpeg'});
              blob.name = 'file.jpg';
              $scope.obj.flow.addFile(blob);
          });
        });
      });

答案 2 :(得分:0)

我在此提供的解决方案基于此处的帖子:

Creating a Blob from a base64 string in JavaScript

我面临类似的情况,但是使用Base64将图像存储在服务器上。当加载网页并从数据库中检索图像时,必须将这些图像添加回flow.files数组。使用Base64字符串将图像保存在数据库中。因此,在页面加载期间,我唯一的方法是将Base64字符串转换为Blob并将文件添加回flow.files数组。

这使得流控制器在从数据库加载页面后能够正常运行。

以下是步骤:

  1. 添加指令load-photo并将其添加到输入元素additional_image1,该元素具有使用jQuery从文档就绪事件中的数据库加载的Base64字符串。

  2. 添加一个指令以访问该元素并调用范围函数$scope.loadPhoto准备加载照片。

  3. 在加载照片功能中,将Base64转换为Blob并将文件添加到流控制中。

  4. 确保范围变量$scope.imageStringB64和输入元素additional_image1手动同步,因为ng-model没有按预期工作。这是因为angular之外的jQuery代码正在从数据库加载输入元素,我发现它们没有动态绑定。

  5. JavaScript代码:

    app.directive('loadPhoto', function () {
        return function (scope, element, attrs) {
            //This directive 'load-photo' is required to access the DOM element inside the scope
            //This will get the Base64 string of the image which is stored in the input element
            angular.element(document).ready(function () {
                scope.loadPhoto(element[0]);
            })
        }
    })
    
    app.controller('photosController', ['$scope', '$http', '$timeout',
        function ($scope, $http, $timeout) {
            ...
            var BLANK_IMG_URL = "//:0";
            $scope.removeFile = function () {
                //debugger;
                $scope.$flow.cancel();
                $scope.imageStringB64 = '';
                $scope.imageString = BLANK_IMG_URL;
            }
            $scope.loadPhoto = function (elem) {
                //Load photo from Database
                //The photo Base64 is stored in the input element 'elem'
                var blobImage;
                var tmpBase64;
                tmpBase64 = angular.element(elem).val(); 
                if (tmpBase64) {
                    //Convert Base64 to Blob object
                    blobImage = b64toBlob(tmpBase64, 'image/png');
                    blobImage.name = "image.png";
                    //Add the Blob object to flow files.
                    $scope.$flow.addFile(blobImage);
                }
            }
            ...
    }]);
    

    HTML代码:

                        <div class="photo-wrapper"  ng-controller="photosController" 
                            flow-init
                            flow-file-added="!isAppraiserSigned() && !!{png:1,gif:1,jpg:1,jpeg:1}[$file.getExtension()]"
                            flow-files-submitted="$flow.upload()">
                            <h4 class='photo-title'>Photo 1</h4>
                            <div class="property-photo drag-drop-photo" ng-hide="$flow.files.length" flow-drop
                                flow-drag-enter="isAppraiserSigned()?style={}:style={border:'4px solid green'}" flow-drag-leave="style={}" ng-style="style">
                                <div class='drag-drop-lbl'>Drop file here</div>
                            </div>
                            <div class="property-photo" flow-drop ng-show="$flow.files.length" 
                                flow-drag-enter="isAppraiserSigned()?style={}:style={border:'4px solid green'}" flow-drag-leave="style={}" ng-style="style">
                                <img id="additional_image1_section" style="max-height:100%" flow-img="$flow.files[0]" />
                                <input id="additional_image1" name = "additional_image1" ng-hide="true" type="text" ng-model="imageStringB64" load-photo/>                      
                            </div>
                            <div>
                                <a href="#" class="btn" ng-hide="$flow.files.length" flow-btn flow-attrs="{accept:'image/*'}"><%=selectImageLbl%></a>
                                <a href="#" class="btn" ng-show="$flow.files.length" flow-btn flow-attrs="{accept:'image/*'}">Change</a>
                                <a href="#" class="btn btn-danger" ng-show="$flow.files.length"
                                   ng-click="removeFile()">
                                  Remove
                                </a>
                            </div>
                            <div class='photo-description'>
                                <label class='description-lbl' for='additional_image_describe1'><%=descriptionLbl%></label>
                                <input class='description' id='additional_image_describe1' name='additional_image_describe1' type="text" />
                            </div>
                        </div>
    

    有关将Base64图像转换为blob并返回Base64的更多选项,请参阅此代码示例:

    fiddle.jshell.ne