前台读取后台传入的二进制流并转成图片

生成随机字符串:

function randomString(len) {
	len = len || 32;
	var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	var maxPos = $chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return str;
}

len为要生成的字符串长度。

 

由于 ajax 不能获取到二进制数据,所以用原生的 DOM 操作:

                var name = randomString(10);
		var data = {"name": name, "otpSk": "BGIVA4SZTMP52KB6UXUGI73V4HWAIORK6KTD6LPSJCMWOEODFN2A"};
		var xhr = new XMLHttpRequest();
		xhr.open('POST', 'http://localhost:10005/api/getImage', true);
		xhr.responseType = "arraybuffer";
		xhr.onload = function (event) {
			// var arrayBuffer = xhr.response;
			/* var blobBuilder = new BlobBuilder();
			blobBuilder.append(oReq.response);
			var blob = blobBuilder.getBlob("image/png"); */
			//var byteArray = new Uint8Array(arrayBuffer);
			//document.getElementById("qrcode").src = byteArray;
			
			// 方法一:
			var byteArray = new Uint8Array(xhr.response);
			var binary = '';
			for (var i = 0; i < byteArray.length; i++) {
				binary += String.fromCharCode(byteArray[i]);
			}
			var imageType = xhr.getResponseHeader("Content-Type");
			$('#qrcode').attr("src", "data:" + imageType + ";base64," + window.btoa(binary));
			
			// 方法二:
			/* var imageType = xhr.getResponseHeader("Content-Type");
			var blob = new Blob([xhr.response], { type: imageType });
			var imageUrl = (window.URL || window.webkitURL).createObjectURL(blob);
			$('#qrcode').attr("src", imageUrl); */
		};
		xhr.send(JSON.stringify(data));

 

你可能感兴趣的:(JavaScript)