$.ajax /vue-cli axios获取后台响应回来的图片

响应回来一张图片,需要渲染在img标签上

$.ajax

	$.ajax({
    		url: `${serverPath}/validateCode/create`,
    		xhrFields: {
    			responseType: "blob"
    		},
    		contentType: "image/jpeg",
    	}).then(res => {
    		return new Promise((resolve, reject) => {
    			const fileReader = new FileReader();
    			fileReader.onload = (e) => {
    				resolve(e.target.result);
    			};
    			fileReader.readAsDataURL(res);
    			fileReader.onerror = () => {
    				reject(new Error('文件流异常'));
    			};
    		});
    	}).then(res => {
    		// 转化后的base64
    		$(".code-img").attr("src", res);
    	})

vue中axois

this.axios.get(conf.api_base_url + "/validateCode/create/" + this.time, {
						responseType: "arraybuffer"
					})
					.then(response => {
						return 'data:image/png;base64,' + btoa(new Uint8Array(response.data).reduce((data, byte) =>
							data + String.fromCharCode(byte), ''));
					}).then(res => {
						this.codeImgUrl = res;
					})

真是有点笨蛋啊,思考许久,网络也很难救命

猜你喜欢

转载自blog.csdn.net/enhenglhm/article/details/122585664
今日推荐