[03天]不使用file类型input触发文件选择
传统文件浏览上传
想当年,我们在Web端文件上传:
<input type="file">
如果想自定义样式:
<label for="file">自定义样式</label> <input type="file" id="file" style="display: none;">
即使能自定义样式,也必须有一个input:file标签在。
新的API
只需要在操作dom元素时,调用showOpenFilePicker方法即可。
<button id="upload">上传文件</button>
<script>
document.querySelector('#upload').addEventListener('click', () => {
window.showOpenFilePicker().then(res => {
res[0].getFile().then(file => {
console.log(file)
})
})
})
</script>showOpenFilePicker(options)方法返回Promise对象,并同样可以传入参数限定文件类型等浏览条件
options:
multiple
布尔值,默认值是 false ,表示只能选择一个文件。
excludeAcceptAllOption
布尔值,默认值是 false ,表示是否排除下面 types 中的所有的accept文件类型。
types
可选择的文件类型数组,每个数组项也是个对象,支持下面两个参数:
description:表示文件或者文件夹的描述,字符串,可选。accept:接受的文件类型,对象,然后对象的键是文件的MIME匹配,值是数组,表示支持的文件后缀。
目前部分浏览器还未实现。不适合用于正式项目

家族API
showDirectoryPicker() // 可选择目录

showSaveFilePicker() // 下载窗口
function getNewFileHandle() {
const opts = {
types: [{
description: 'Text file',
accept: {'text/plain': ['.txt']},
}],
};
return window.showSaveFilePicker(opts);}
2022-05-19 16:03:48
842
0
参与讨论