Javascript / jQuery - How to convert Media and Image data into binary text format

后端 未结 2 1839
情话喂你
情话喂你 2021-01-27 14:14

I need to send a image/media through json, for that conversion needs to be done into text format. How can I achieve that through jQuery/ Javascript?

2条回答
  •  生来不讨喜
    2021-01-27 14:29

    A few times already I read that jQuery doesn't provide functionality to download binary data and have it pass on to JavaScript as a string. Then I ran into this question. That got me thinking and I wrote a wrapper around $.ajax() looking like this (yes, it's simplified to show the main bits):

    ajaxWrapper = function(url, dataType, callback, headers) {
        return $.ajax({
            url: url,
            dataType: dataType == "binary" ? "text" : dataType,
            mimeType: dataType == "binary" ? "text/plain; charset=x-user-defined" : undefined,
            headers: headers || {}
        }).done(function(data, status, jqXHR) {
            callback(data, status, jqXHR);
        });
    }
    

    And then in case you are dealing with Unicode the callback contains this line:

    data = btoa(unescape(encodeURIComponent(data)));
    

    or otherwise simply

    data = btoa(data);
    

    In other words if you read through the documentation of $.ajax() you simply add a dataType "binary".

    Note that I use jQuery 1.7.1, but I don't see why it shouldn't work in later versions, too.

提交回复
热议问题