load and display PNG image (Not base64) requiring basic authentication in JavaScript

前端 未结 1 1674
清歌不尽
清歌不尽 2021-01-23 16:53

I\'m so stuck on this. I need to retrieve a picture e.g. http://ip:port/icon_contact.png using JavaScript from another server requiring basic authentication. The server can\'t g

相关标签:
1条回答
  • 2021-01-23 17:18

    If I'm reading your question correctly — which is by no means certain — you want to retrieve the binary data of an image file providing basic authentication information directly (not via the user).

    You should be able to do this with the XMLHttpRequest object (you can supply auth information in the open call), but to read binary data from the response I'm fairly sure you'll have to stray into brand-new and/or implementation-specific stuff. Here are links to the MSDN, MDC, and (fairly new) W3C docs. Microsoft's XMLHttpRequest has responseBody, Mozilla's (Firefox's) has mozResponseArrayBuffer, and I believe the W3C docs discuss binary data here.

    To display the image having loaded it via the above, you could transform the binary data into a data URL (more correctly "data URI", but no one says that) string and assign the result to an img tag's src. You'd have to convert from whatever the browser-specific binary stuff was into the base64 encoding (for the data URL). (You probably don't have to write the conversion yourself, a quick search indicates that people have been tackling this problem and you can reuse [and possibly contribute back to] their efforts...)

    The bad news is that IE only supports data URIs as of IE8, and it limits them to 32k, so you'd have to nifty slicing techniques like Google does for search preview.

    Once you have the data:// string, the img tag part is easy. If you're not using a library:

    var img, element;
    
    img = document.createElement('img');
    img.src = /* ... the data URI ... */
    element = /* ... find the element you want to put the image in, via
                     document.getElementById or document.getElementsByTagName
                     or other DOM traversal ... */;
    element.appendChild(img);
    
    0 讨论(0)
提交回复
热议问题