$http.get from jpg to img

2019-09-11 17:41发布

I'm trying to load one image with $http.get because it'll later come from the server, and I dont really know what to do:/

the code I have now is:

in the service i get like this:

return $http.get('resources/mock-data/image.jpg', {
      headers: {
        'Content-Type': 'image/jpg'
      }
    });

that returns me a promisse, that comes with a binary data like this: ����JFIF��� ( %!1!%),...383,7(-.+

,$&,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,�������K!1AQ"aq��2���BRr�#3b����$4S���Ccst���5D������< !1AQ"aq�����2���3Br�#$4b�C����R��?��� Ԑ-�o>�vJ4�>�aW�s̯�����I�&��ϻ��sl���Z��.�6-���-�r�R�hK;���֮�T!� �k����R [�Muw�EKO����Cً����p��(LJ ���nUjul�5m�v>}�ԙҺʵ��ڸ��x��c]���+ Ո ($(����(�s{�g��y���0�w'���#^d�i�k I>�'WJpJQ������^�}:��c�g#�G�^��5N��v<�ҡ��i���fJ�k�ul��9����6zKe��٘|Zۭ��W��)�'�:�j�L�qU�x������b��9RVg5�� (jI5AV\F�\�1�4�G�� 9� (� h�k9�#H+��1�sȂ��K������@{�\�W)T]#��m�Ӕ�U��_��B=�&�a��Θx�l�]nΛfX_2y8���Q������4\�+�O��0!�~̱�t;�����K^�+��5������_H�UQ��v��k��&;������RV�ó�����I�x���]���2ڟB� Ԑ% (@�,��E:5&.P���{R���IŘ��R:8|4����ػ����H�0X W�r��5�l�g�G��p����l���Ǜ1���� �V���0�{'��� ��C�ʴ�#�M�~͟��i�>I�ÿ��0�-}����<��5�V��JT�v����f3�b;��Vg3����P@�@!�%/lk�S����ᔂʘx�۵�9�=p���-������ٽ��m�q��E(��K%�]ż[w�gѾ�+%�m�l8^�Vn���!@��қ��

that is just a part of it... it is 12500 of length...

on the controller i get like this to parse to base64:

var base64 = 'data:image/jpg;base64,' + btoa(unescape(encodeURIComponent(image.data)))
  console.log(base64);
  $scope.fullImage = base64;

where the image is the response of the promisse, and data is where the binary i putted above is.

my view has the following:

  <img ng-src="{{fullImage}}" class="coolin_home_full_image"/>

so, anybody has any idea on how to fix this

1条回答
做自己的国王
2楼-- · 2019-09-11 18:12

I finally figured out what was it.

I was calling the $http get without the header, so it was not returning me a bufferArray but a string, i fixed with:

var deferred = $q.defer();
    var promise = deferred.promise;
    $http.get('resources/mock-data/image.jpg', {}, {
      headers: {
        'Content-Type': 'image/jpg'
      },
      responseType: 'blob'
    }).then(function(image) {
      var blob = new Blob([image.data], {
        type: 'image/jpeg'
      });
      var fr = new FileReader();
      fr.onload = function() {
        deferred.resolve(fr.result);
      };
      fr.readAsDataURL(blob);
    }, function(error) {
      deferred.reject(error);
    });

    return promise;

and then in the controller you call just the return of the promise and throws inside a img like

<img ng-src="{{fullImage}}" />
查看更多
登录 后发表回答