一、文件上传
1、上传的html
我们可以使用input实现文件上传
<input type="file" id="upload">
2、访问上传的文件
通过dom访问
const input = document.querySelector("#upload");const files = input.files;
通过onchange事件访问
const input = document.querySelector("#upload");input.addEventListener('change',function(){// 通过onchange事件获取files,函数要使用function定义,箭头函数this指向父级作用域const files = this.files;},false);input.addEventListener('change',(e) => {// 这个本质还是通过Dom获取文件const files = e.target.files;},false);
3、自定义input
通常,我们在实际的开发中不会真的去使用input标签原本的样式,我们需要实现自己想要的按钮,或者其他的样式.这个时候,我们需要对input的样式进行定制.input上传,无非就是点击input的按钮=>弹出弹窗=>选择文件=>获取文件=>完成上传这么一个过程.如果我们自己写一个button,用自定义的button触发input就可以代替input进行上传文件了.所以我们可以隐藏input,用任意dom元素通过click代理input的点击事件.原理就说到这里.
const input = document.querySelector("#upload");/* 通过调用input.click(),可以唤起文件选择弹窗,* 所以你可以在button的点击事件里去调用这个方法,达到代理的目的*/input.click();
二、文件预览
方法1:通过FileReader实现
const input = document.querySelector("#upload");input.addEventListener('change',function(){const files = this.files;const fileList = Object.entries(files).map(([_,file]) => {const reader = new FileReader();reader.readAsDataURL(file);reader.onload = (e) => {file.preview = e.target.result;}return file;});/* * file中的preview存的就是可以预览使用url,如果你需要保证fileList的顺序,* 请不要使用这种方式,你可以采用索引的方式存储,来保证它的顺序一致性*/console.log(fileList);},false);
方法2:通过window.URL.createObjectURL()实现
const input = document.querySelector("#upload");input.addEventListener('change',function(){const files = this.files;const fileList = Object.entries(files).map(([_,file]) => {const preview = window.URL.createObjectURL(file);file.preview = preview;// 需要在合适的实际进行销毁,否则只有在页面卸载的时候才会自动卸载.// window.URL.revokeObjectURL(preview);return file;});/* * file中的preview存的就是可以预览使用url*/console.log(fileList);},false);
三、拖拽上传
// 此处定义一个drop容器(省略),并取到该元素;const dropBox = document.querySelector("#drop");dropBox.addEventListener("dragenter",dragEnter,false);dropBox.addEventListener("dragover",dragOver,false);dropBox.addEventListener("drop",drop,false);function dragEnter(e){e.stopPropagation();e.preventDefault();}function dragOver(e){e.stopPropagation();e.preventDefault();}function drop(e){// 当文件拖拽到dropBox区域时,可以在该事件取到filesconst files = e.dataTransfer.files;}