How to parse into base64 string the binary image from response?

后端 未结 6 1190
广开言路
广开言路 2020-11-30 02:49

I want to parse the requested image from my REST API into base64 string.

\"enter

6条回答
  •  失恋的感觉
    2020-11-30 03:18

    instead of looping through the blob with _arrayBufferToBase64(), use apply() to do the conversion, it's 30 times faster in my browser and is more concise

    // http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
    function fetchBlob(uri, callback) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', uri, true);
      xhr.responseType = 'arraybuffer';
    
      xhr.onload = function(e) {
        if (this.status == 200) {
          var blob = this.response;
          if (callback) {
            callback(blob);
          }
        }
      };
      xhr.send();
    };
    
    fetchBlob('https://i.imgur.com/uUGeiSFb.jpg', function(blob) {
      var str = String.fromCharCode.apply(null, new Uint8Array(blob));
      console.log(str);
      // the base64 data: image is then
      // ''	
    });

提交回复
热议问题