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

Populate ng-flow with jpeg/jpg as blob

本文关键字:ng-flow 作为 blob 填充 jpg jpeg      更新时间:2023-09-26

我目前正在尝试用我的网络服务器(nodejs http-server)中的图像填充ng-flow,我发现了这个线程:

使用 ng-flow.js 从 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

如果我在谷歌开发控制台中查看响应数据,会有很多问号(它无法显示我猜的字符)。

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

我做了一些结合 cvjensen 解决方案和 penner 的解决方案在用 ng-flow 填充图像文件.js 从 json

控制器:

首先,我从 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 };
                }
            }
          );
        }
    };
  }]);

我最终这样做了。

我的$resource函数如下所示:

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

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

在 JavaScript 中从 base64 字符串创建 Blob

我遇到过类似的情况,但是图像使用 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 代码正在从数据库加载输入元素,我发现它们不是动态绑定的。

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

网页代码:

                    <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