Using the Files API, web content can ask users to select local files and then read the contents of those files. This selection can be done using the HTML <input type="file">
element or via drag and drop.
1. Use the hidden file input element through the click() method
You can hide the admittedly ugly file <input> element and display your own interface to open the file picker and then display which Or which files were selected by the user. You can add the display:none
style to the input element, and then call the <input> element's < a i=6>click() method to achieve.
<input
type="file"
id="file"
multiple
accept="image/*"
style="display:none" />
<button id="uploadBut" type="button">选择一些文件</button>
const uploadBut = document.getElementById("uploadBut");
const file = document.getElementById("file");
// 用户点击文件上传按钮
uploadBut.addEventListener(
"click",
(e) => {
if (file) {
file.click();
}
},
false,
);
// input type:file 的change事件触发,执行拿到上柴男文件列表
file.addEventListener('change', () => {
console.log(file.files);
})
2. Use drag and drop to select files
<div class="dropbox">拖拽上传文件</div>
let dropbox = document.querySelector('.dropbox')
dropbox.addEventListener("dragenter", dragenter, false)
dropbox.addEventListener("dragover", dragover, false)
dropbox.addEventListener("drop", drop, false)
dropbox.addEventListener('dragleave', dragleave, false)
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
// 进入拖拽容器
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
// 离开拖拽容器
function dragleave(e) {
e.stopPropagation();
e.preventDefault();
}
// 将拖拽标签放在拖拽容器上(鼠标松开)
function drop(e) {
e.stopPropagation();
e.preventDefault();
const dt = e.dataTransfer;
const files = dt.files;
console.log(dt.files);
}
Example: Case - Drag and drop to upload files and generate thumbnails - CSDN Blog