This article mainly brings you an example of selecting images with input type=file and achieving preview effects. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Through the tag, specify the type as file, which can provide file upload;
accept: You can choose the upload type, such as: just upload pictures, and there are no restrictions The image format is image/*;
multiple: specifies whether multiple files can be selected;
specifies that only pictures can be uploaded, and multiple files can be selected
<input type="file" accept="image/*" multiple="multiple"/>
Of course , a direct input type=file can only select uploaded files/resources. If we need to achieve the preview effect on the current page after selecting the image, then we can achieve it in the following way
HTML code
<body> <p id="box"> <img id="imgshow" src="" alt=""/> </p> <p id="pox"> <input id="filed" type="file" accept="image/*"/> </p> </body>
css style file
<style> #box{ width: 300px; height: 300px; border: 2px solid #858585; } #imgshow{ width: 100%; height: 100%; } #pox{ width: 70px; height: 24px; overflow: hidden; } </style>
JS code
<script> //在input file内容改变的时候触发事件 $('#filed').change(function(){ //获取input file的files文件数组; //$('#filed')获取的是jQuery对象,.get(0)转为原生对象; //这边默认只能选一个,但是存放形式仍然是数组,所以取第一个元素使用[0]; var file = $('#filed').get(0).files[0]; //创建用来读取此文件的对象 var reader = new FileReader(); //使用该对象读取file文件 reader.readAsDataURL(file); //读取文件成功后执行的方法函数 reader.onload=function(e){ //读取成功后返回的一个参数e,整个的一个进度事件 console.log(e); //选择所要显示图片的img,要赋值给img的src就是e中target下result里面 //的base64编码格式的地址 $('#imgshow').get(0).src = e.target.result; } }) </script>
*JQuery is used in the above js code, so the jQuery file must be introduced
Related recommendations:
File Control Select Picture Example Tutorial
The input image will not be uploaded and displayed in time after selecting it
The above is the detailed content of Detailed explanation of input type=file to select pictures and achieve preview effects. For more information, please follow other related articles on the PHP Chinese website!