【问题标题】:returning image/jpeg as arraybuffer or blob将图像/jpeg 作为 arraybuffer 或 blob 返回
【发布时间】:2018-05-26 12:05:54
【问题描述】:

我目前正在调用我的 api,它返回一个图像为 image/jpeg。我的问题是当通过javascript angular .factory资源调用url时,我的数组缓冲区为空{}。此外,字节长度为 0。如果我使用响应类型“”或“文本”调用 api url,我确实会看到多种类型的值。我在这里想念什么?感谢您的帮助!

JS:

.factory("Img", function($resource) {
    return $resource("http://mypathTo/image/:id", {
      id: "@id"
    }, {
      responseType: '' //arraybuffer return empty
    });
  });

app.controller //代码

    $scope.getImage = function(productid) {
      console.log(productid);
      par = {id: [productid]};
      Img.getImage(par).$promise.then(
        function(data){
          console.log("success:" + data); //I am able to see bytes when coming back as text but not with arraybuffer as data.bytelength = 0
          scope.productionPicturePath = data;
          return data;
        },
        function(data){
          console.log("error" + data);
        }
      );
    }
}

【问题讨论】:

  • $resource 服务只能根据isArray 返回 JavaScript 对象或数组。要获取 ArrayBufferBlob 等奇异对象,请使用 $http service
  • 您必须设置其他选项,例如transformResponse
  • @georgeawg 感谢您的回复,我实际上能够实现这一点并收到了一些回复!谢谢!
  • 阅读@george 提供的链接中的文档。默认是将响应从 json 解析为对象/数组,这绝对不是您正在使用的
  • 向我们展示您使用默认 responseType 获得的响应示例。

标签: javascript angularjs angularjs-http


【解决方案1】:

$resource 服务只能根据isArray 返回 JavaScript 对象或数组。要获取 ArrayBufferBlob 等奇异对象,请使用 $http service

The DEMO

angular.module("app",[])
.controller("ctrl", function($scope,$http) {
    var vm = $scope;
    var url="//i.imgur.com/fHyEMsl.jpg";

    var config = { responseType: 'blob' };
    $http.get(url,config)
      .then(function(response) {
        console.log("OK");
        //console.log(response.data);
        vm.blob = response.data;
        vm.dataURL = URL.createObjectURL(vm.blob);
        console.log(vm.dataURL);
    }).catch(function(response) {
        console.log("ERROR");
        throw response;
    });
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="ctrl">
      BLOB type {{blob.type}}<br>
      BLOB size {{blob.size}}<br>
    <img ng-src="{{dataURL}}" height="100" />
  </body>

【讨论】:

  • 成功了,感谢您的帮助,演示帮助了很多!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2015-10-28
  • 2019-06-27
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
相关资源
最近更新 更多