$.ajax /vue-cli axios to get the picture returned by the background response

The response returns an image, which needs to be rendered on the img tag

$.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);
    	})

axois in vue

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;
					})

I'm really a bit stupid. After thinking for a long time, the Internet is difficult to save my life.

Guess you like

Origin blog.csdn.net/enhenglhm/article/details/122585664