選擇文件
此方式不需要創(chuàng)建多余的html標簽,非常適合項目開發(fā)中使用。文章來源地址http://www.zghlxwxcb.cn/news/detail-828598.html
<button onclick="readFile()">選擇文件</button> <script> // 不支持xlsx/docx等微軟文件格式 async function readFile() { try { // 讀取文件 const [fileHandle] = await window.showOpenFilePicker(); const file = await fileHandle.getFile(); let reader = new FileReader(); reader.onload = ({ target: { result } }) => { console.log(`-------輸出結(jié)果-------\n${result}`); } reader.readAsText(file, 'utf-8'); } catch (error) { console.error('Error selecting file:', error); } } </script>
選擇文件夾
<button onclick="chooseFolder()">選擇文件夾</button>
<script>
// 選擇文件
async function chooseFolder() {
try {
let handle = await showDirectoryPicker(),
root = await processHandle(handle);
for(let i = 0;i < root.child.length; i++) {
readFile(root.child[i])
}
} catch (error) {
console.log(error);
// 用戶拒絕的處理
}
}
// 解析文件夾
async function processHandle(handle) {
if (handle.kind === 'file') return handle;
handle.child = [];
// 得到異步迭代器
let iter = handle.entries();
for await (let item of iter) {
handle.child.push(await processHandle(item[1]));
}
return handle;
}
// 讀取文件內(nèi)容
function readFile(fileHandle) {
let file = await fileHandle.getFile(),
reader = new FileReader();
reader.onload = ({ target: { result } }) => {
console.log(result);
}
reader.readAsText(file, 'utf-8');
// kind: "directory" 表示選擇的是文件
// name: "aText" 文件名字
}
</script>
完整版
<div class="p_20 bs_bb">
<div class="bs_bb p_10 d_f jc_se bc_rgba_68_68_86_05">
<button class="fs_30 cursor_pointer" onclick="chooseFile()">選擇文件</button>
<button class="fs_30 cursor_pointer ml_20" onclick="chooseFolder()">選擇文件夾</button>
</div>
</div>
<script>
// 選擇文件
async function chooseFile() {
// 創(chuàng)建用于存放文件句柄的變量
let fileHandle = undefined;
// 打開文件選擇器,解構(gòu)返回的數(shù)組中的第一個元素
[fileHandle] = await window.showOpenFilePicker();
readFile(fileHandle);
}
// 選擇文件夾
async function chooseFolder() {
try {
let handle = await showDirectoryPicker(),
root = await processHandle(handle);
for (let i = 0; i < root.child.length; i++) readFile(root.child[i]);
} catch (error) {
// 用戶拒絕的處理
console.log(error);
}
}
// 解析文件夾
async function processHandle(handle) {
if (handle.kind === 'file') return handle;
handle.child = [];
// 得到異步迭代器
let iter = handle.entries();
for await (let item of iter) {
handle.child.push(await processHandle(item[1]));
}
return handle;
}
// 獲取文件內(nèi)容
async function readFile(fileHandle) {
let file = await fileHandle.getFile(),
reader = new FileReader();
reader.onload = ({ target: { result } }) => {
console.log(`-------輸出結(jié)果-------\n${result}`);
}
reader.readAsText(file, 'utf-8');
// kind: "directory" 表示選擇的是文件
// name: "aText" 文件名字
}
</script>
文章來源:http://www.zghlxwxcb.cn/news/detail-828598.html
到了這里,關(guān)于web前端之JavaScript選擇文件和文件夾、全程使用WebApi操作文件、不涉及html、showOpenFilePicker、showDirectoryPicker的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!