The front end obtains local images and converts them into base64 format

Today I saw various online operations on how to obtain and convert front-end images into base64 format. It turns out that there are experts among the people. It’s amazing. I didn’t expect there to be so many methods, so I’ll write my own method. I’m used to using filereader
. The built-in class feels relatively simple. You don’t need to worry about the internal principles. You can just get the picture and transmit it on the Internet!
First, we need to use input (file type) and a button element. One is responsible for uploading images, and the other is responsible for processing images. In the processing function, the files and readasdataurl methods are used to achieve image conversion:
element

<div class="mybox">
			<input type="file" name="" id="sendimg">
			<button onclick="handleimg()">处理</button>
		</div>

function

function handleimg()
		{
    
    
			console.log('点击了');
			var img=document.getElementById('sendimg')
			img=img.files
			const reader=new FileReader()
			reader.readAsDataURL(img[0])
			reader.onload=function()
			{
    
    
				console.log(this.result);
			}
		}

The above this.result is the base64 result.
Insert image description here
That’s it for today’s sharing! !

Guess you like

Origin blog.csdn.net/weixin_51295863/article/details/131691365