javascript 将URL转换为Blob、base64

<script>
			// 图片地址 转为 blob 、base64格式 imgUrl类型为字符串string
			function base64ByURL (imgUrl) {
            // 两大重点 Promise  XMLHttpRequest
				return new Promise(resolve => {
					var xhr = new XMLHttpRequest();
					xhr.open("get", imgUrl, true);
					xhr.responseType = "blob";
					xhr.onload = function () {
						if (this.status == 200) {
							let blob = this.response;
							let oFileReader = new FileReader();
							oFileReader.onloadend = function (e) {
								resolve({blob,base64:e.target.result})
							};
							oFileReader.readAsDataURL(blob);
						}
					};
					xhr.send();
				});
			};


			// 调用
			base64ByURL().then(res=>{
				let {blob,base64} = res;
				console.log(blob,base64,"blob,base64")
			});
</script>

  

posted @ 2024-07-30 05:26  时光SHG  阅读(186)  评论(0编辑  收藏  举报