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

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

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

\"enter

6条回答
  •  温柔的废话
    2020-11-30 02:56

    I think part of the problem you're hitting is that jQuery.ajax does not natively support XHR2 blob/arraybuffer types which can nicely handle binary data (see Reading binary files using jQuery.ajax).

    If you use a native XHR object with xhr.responseType = 'arraybuffer', then read the response array and convert it to Base64, you'll get what you want.

    Here's a solution that works for me:

    // 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) {
      // Array buffer to Base64:
      var str = btoa(String.fromCharCode.apply(null, new Uint8Array(blob)));
    
      console.log(str);
      // Or: ''
    });

    https://jsfiddle.net/oy1pk8r3/2/

    Produces base64 encoded console output: /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAw.....

提交回复
热议问题