get an image file with XMLHttpRequest and encode with base64
2014-11-25 21:16
579 查看
var xhr = new XMLHttpRequest(); var imgurl = "http://lh5.ggpht.com/-ZpKKJYkqobU/ULk2lb2yh5I/AAAAAAAAAAA/z74Pv1Zbfjc/photo.jpg"; xhr.open('GET', imgurl, true); xhr.responseType = 'arraybuffer';//watch out this line! xhr.onload = function(){ var blob = new Uint8Array(this.response); //encode with base64 var uri = "data:image/jpeg;base64," + Base64.encode(blob); document.getElementById("myImage").src = uri; }; xhr.send();
following is the very simple Base64 encode algorithm
var Base64 = { _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; //input = Base64._utf8_encode(input); //comment out to encode binary file(like image) while (i < input.length) { chr1 = input[i++]; chr2 = input[i++]; chr3 = input[i++]; enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) + Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4); } return output; } }
相关文章推荐
- How To Do A JavaScript Cross-Domain POST or GET With jQuery or XMLHttpRequest
- POST a string and an image in one request using HttpClient
- Thread-safe caching object with file and HTTP implementations
- Save an XML File to Database and Send an Email using XSLT
- Ajax using XMLHttpRequest and Struts
- [Yii Framework] How to develop an extension with image, css and js
- [转]cross-site xmlhttprequest with CORS
- Ajax using XMLHttpRequest and Struts
- Dynamic HTML and XML: The XMLHttpRequest Object
- 几个http请求相关的函数 HttpWebRequest: Post , Get ; PostAndRedirect
- ajax XMLHttpRequest post get
- XML Web Service初体验: HTTP-GET, HTTP-POST and SOAP的比较
- XML Web Service初体验: HTTP-GET, HTTP-POST and SOAP的比较
- securely implement request processing, filtering and content redirection with HTTP pipeline in ASP.NET
- XML Web Service初体验: HTTP-GET, HTTP-POST and SOAP的比较
- Get MSN ADS by xmlHttpRequest
- XML Web Service初体验: HTTP-GET, HTTP-POST and SOAP的比较
- getHttpObject , Microsoft.XMLHTTP , XMLHttpRequest
- 转:Working with HttpWebRequest and HttpWebResponse in ASP.NET
- 原始ajax通过xmlHttpRequest对象的send()方法提交数据--Get方式和Post方式