Using jQuery's ajax method to retrieve images as a blob

前端 未结 3 2213
南旧
南旧 2020-11-22 10:36

I recently asked another (related) question, which lead to this follow up question: Submitting data instead of a file for an input form

Reading through the jQuery.aj

3条回答
  •  野性不改
    2020-11-22 10:59

    If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

    So you will have to modify the responseType to "blob" only if it is a successful call:

    $.ajax({
        ...
        xhr: function() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 2) {
                    if (xhr.status == 200) {
                        xhr.responseType = "blob";
                    } else {
                        xhr.responseType = "text";
                    }
                }
            };
            return xhr;
        },
        ...
        error: function(xhr, textStatus, errorThrown) {
            // Here you are able now to access to the property "responseText"
            // as you have the type set to "text" instead of "blob".
            console.error(xhr.responseText);
        },
        success: function(data) {
            console.log(data); // Here is "blob" type
        }
    });
    

    Note

    If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

    The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

提交回复
热议问题