前端获取文件夹内文件

发布时间:2026/6/25 20:59:36
前端获取文件夹内文件 · 通过 input file 实现获取文件夹里的所有文件el-buttontypeprimaryclickopenFileInput选取文件夹/el-buttoninputtypefilerefdirInputwebkitdirectorydirectorystyledisplay:none;changechangeFileInputopenFileInput(type){this.$refs.dirInput.click();}changeFileInput(e){if(e.target.files.length0){this.$message.error(未选择任何文件或文件夹);return;}letfileList[]Array.from(e.target.files).forEach(file{constfileNamePartsfile.name.split(.);if(fileNameParts[1]!json)return;constnamefileNameParts[0]fileList.push({name:name,path:file.webkitRelativePath,})})}· 获取文件具体内容/** * 获取本地文件内容 * param {string} filePath - 本地文件的路径相对路径或绝对路径 * returns {Promisestring} 返回文件内容的 Promise */asyncgetLocalFile(filePath){try{constresponseawaitfetch(filePath);// 如果请求失败例如文件不存在返回 404抛出错误if(!response.ok){thrownewError(请求失败:${response.status}${response.statusText});}// 将响应体解析为文本并返回returnawaitresponse.text();}catch(error){console.error(获取文件时发生错误:,error.message);throwerror;// 继续向上抛出错误便于调用者处理}}