H5——(JQ/Native Implementation) Page upload pictures

Regarding the original things, at least I have forgotten a lot, just record. This is also a more commonly used function of H5.

Need/Question: Click the button, select the picture, verify, upload

Don't talk nonsense, just go to the code

<!DOCTYPE html>
<html>
<head>
</head>
<body >
<button id="subimg"  onclick="ome()">来了老弟</button>
<input type="file" multiple id='getfile'  onchange="add(this)" ></input>
<img src="./20201201111431.jpg" id="myimg" style="height: 250px;"/>
</body>
<script >
	let myimg =document.getElementById('myimg')
	let subimg =document.getElementById('subimg')
	let getfile =document.getElementById('getfile')
	
	function ome() {
    
    
		getfile.click()   //触发上传控件
	}
	function add(f) {
    
    
			// console.log(f.files[0].type)    //图片格式
			// console.log(f.files[0].size)    //图片大小做判断
			// 解析预览
			let reader = new FileReader()
			reader.readAsDataURL(f.files[0])
			reader.onload = function () {
    
    
			  // console.log( reader.result)  //base64格式的图片
			  myimg.src=reader.result
			}
			//上传时候也是传的f.files[0]文件。
	}
</script>
</html>

Click ""Here is my brother"" to trigger the file selection control. Only when the picture is selected will add() be triggered.
真实项目中是不会修改“选择文件“控件的样式的,更不会留他在页面上。都是直接隐藏,用更好看的元素代替他

Potholes:

  1. You can only get the parameters by binding the onchange event to the label (you must write this). If you write the monitoring function, you can't get this parameter
  2. 1024 bytes=1kb, 1024kb=1M. 1024 1024 10=10M
  3. Regardless of whether multiple selection is set, it must be a parameter. files[0]

Insert picture description here

Company actual combat

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45629623/article/details/114542537