您好,登錄后才能下訂單哦!
今天小編給大家分享一下Js怎么根據(jù)文件夾目錄獲取Json數(shù)據(jù)輸出demo的相關(guān)知識點,內(nèi)容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> h3 { text-align: center; } #file_input { display: none; } .userBtn { padding: 6px 25px; background: #00bfff; border-radius: 4px; color: white; cursor: pointer; border: none; } .userBtn:active { background-color: #00bfff90; } .userBtn[disabled] { background: #00bfff60; cursor: not-allowed; } #dataShowArea { width: 100%; height: 600px; border: 1px solid #000; box-sizing: border-box; margin-top: 20px; overflow: hidden; padding: 20px; padding-top: 10px; background: #0cff0014; border-radius: 6px; display: flex; flex-wrap: wrap; flex-direction: column; } #dataShowArea #realityArea { width: 100%; flex: 1; overflow: overlay; box-sizing: border-box; margin: 0px; color: #3300ed; /* border: 1px solid #3300ed; */ border-radius: 6px; } #dataShowArea #realityArea::-webkit-scrollbar { display: none; } #dataShowArea .hintUser{ width: 100%; color: #3300ed; text-align: center; font-style: italic; margin-bottom: 10px; } .userBtnArea{ width: 100%; display: flex; align-items: center; justify-content: space-around; } </style> </head> <body> <h3>文件夾路徑生成json文件</h3> <div class="userBtnArea"> <button id="coverInput" class="userBtn" onclick="coverInputClick()">選擇文件夾</button> <button id="saveJson" class="userBtn" onclick="saveJsonFile()" disabled>輸出JSON文件</button> </div> <!-- 選取單個文件夾 --> <input type="file" id="file_input" webkitdirectory directory onchange="outputFile(this.files)" /> <!-- 存放加載文件的數(shù)據(jù)的區(qū)域 --> <div id="dataShowArea"> <div class="hintUser">數(shù)據(jù)預覽</div> <pre id="realityArea" class="hljs"></pre> </div> <script> //全局的文件 json 數(shù)據(jù) let filesData = ''; let obj = document.getElementById('realityArea'); let saveJsonBtn = document.getElementById('saveJson'); </script> </body> </html>
//File 文件格式需要轉(zhuǎn)成 Object => 將字段提出方便裝換 const fileField = [ 'lastModified', 'lastModifiedDate', 'name', 'size', 'type', 'webkitRelativePath', ]; //文件 目錄數(shù)據(jù)生成 async function handleFiles(files) { if (files.length > 0) { let catalogue = { // childer:{} }; for (fileItem of files) { //獲取要插入的對象 => File類型不能直接插入,會報錯 => File類型不歸屬于Object類型 let fileData = {}; fileField.forEach((item) => { fileData[item] = eval(`fileItem.${item}.toString()`); }); //文件的name值為 xx.文件屬性 會在執(zhí)行插入語句時報錯,只拿文件名,不拿文件屬性 fileData.noTypeName = fileData.name.split('.')[0]; let fileData_ = JSON.stringify(fileData); //獲取樹的每個字段 let catalogueField = fileItem.webkitRelativePath.split('/'); //要執(zhí)行的js語句拼接 let objStr = catalogueField.reduce((pre, cur, index, arr) => { /** * pre:上一次調(diào)用返回的值,或者提供的初始值 * cur:數(shù)組中當前處理的元素 * index:數(shù)組中當前處理的元素的下標 * arr:調(diào)用reduce函數(shù)的數(shù)組 * */ if (index >= arr.length - 1) { !eval(pre) && eval(`${pre}={isLeaf:true}`); pre = `${pre}['${fileData.noTypeName}']`; } else { index == 0 ? (pre = `${pre}['${cur}']`) : (pre = `${pre}.Folder['${cur}']`); !eval(pre) && eval(`${pre}={isLeaf:false,type:'folder',Folder:{}}`); } return pre; }, 'catalogue'); eval(`${objStr}={isLeaf:true,...${fileData_}}`); } return catalogue; } }
//寫成json文件輸出 function saveToJson(data) { if (!data) { console.error('json文件的數(shù)據(jù)對象不存在'); return; } var content = JSON.stringify(data, null, '\t'); // 轉(zhuǎn)成blob數(shù)據(jù)對象 var blob = new Blob([content], { type: 'text/plain;charset=utf-8', }); //第二步 => 文件數(shù)據(jù) 轉(zhuǎn)為可以 下載 的地址路徑 改路徑指向文件數(shù)據(jù) let url = window.URL.createObjectURL(blob); //動態(tài)創(chuàng)建a標簽 => 模擬觸發(fā)a標簽的下載 => 用于將生成的json數(shù)據(jù)下載到本地 let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', 'model.json'); document.body.appendChild(link); link.click(); document.body.removeChild(link); //URL.createObjectURL函數(shù)創(chuàng)建的數(shù)據(jù)不會再內(nèi)存刪除 得手動刪除或者瀏覽器轉(zhuǎn)態(tài)退出 window.URL.revokeObjectURL(url); }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> h3 { text-align: center; } #file_input { display: none; } .userBtn { padding: 6px 25px; background: #00bfff; border-radius: 4px; color: white; cursor: pointer; border: none; } .userBtn:active { background-color: #00bfff90; } .userBtn[disabled] { background: #00bfff60; cursor: not-allowed; } #dataShowArea { width: 100%; height: 600px; border: 1px solid #000; box-sizing: border-box; margin-top: 20px; overflow: hidden; padding: 20px; padding-top: 10px; background: #0cff0014; border-radius: 6px; display: flex; flex-wrap: wrap; flex-direction: column; } #dataShowArea #realityArea { width: 100%; flex: 1; overflow: overlay; box-sizing: border-box; margin: 0px; color: #3300ed; /* border: 1px solid #3300ed; */ border-radius: 6px; } #dataShowArea #realityArea::-webkit-scrollbar { display: none; } #dataShowArea .hintUser{ width: 100%; color: #3300ed; text-align: center; font-style: italic; margin-bottom: 10px; } .userBtnArea{ width: 100%; display: flex; align-items: center; justify-content: space-around; } </style> </head> <body> <h3>文件夾路徑生成json文件</h3> <div class="userBtnArea"> <button id="coverInput" class="userBtn" onclick="coverInputClick()">選擇文件夾</button> <button id="saveJson" class="userBtn" onclick="saveJsonFile()" disabled>輸出JSON文件</button> </div> <!-- 選取單個文件 --> <!-- <input type="file" id="file" onchange="handleFiles(this.files)" /> --> <!-- 選取多個文件 --> <!-- <input type="file" id="file_input" multiple="multiple" onchange="handleFiles(this.files)" /> --> <!-- 選取單個文件夾 --> <input type="file" id="file_input" webkitdirectory directory onchange="outputFile(this.files)" /> <!-- 存放加載文件的數(shù)據(jù)的區(qū)域 --> <div id="dataShowArea"> <div class="hintUser">數(shù)據(jù)預覽</div> <pre id="realityArea" class="hljs"></pre> </div> <script> //全局的文件 json 數(shù)據(jù) let filesData = ''; let obj = document.getElementById('realityArea'); let saveJsonBtn = document.getElementById('saveJson'); //按鈕點擊觸發(fā)input標簽的點擊 function coverInputClick() { document.getElementById('file_input').click(); } //報錯json文件 function saveJsonFile(data) { saveToJson(filesData); } //File 文件格式需要轉(zhuǎn)成 Object => 將字段提出方便裝換 const fileField = [ 'lastModified', 'lastModifiedDate', 'name', 'size', 'type', 'webkitRelativePath', ]; //文件 目錄數(shù)據(jù)生成 async function handleFiles(files) { if (files.length > 0) { let catalogue = { // childer:{} }; for (fileItem of files) { //獲取要插入的對象 => File類型不能直接插入,會報錯 => File類型不歸屬于Object類型 let fileData = {}; fileField.forEach((item) => { fileData[item] = eval(`fileItem.${item}.toString()`); }); //文件的name值為 xx.文件屬性 會在執(zhí)行插入語句時報錯,只拿文件名,不拿文件屬性 fileData.noTypeName = fileData.name.split('.')[0]; let fileData_ = JSON.stringify(fileData); //獲取樹的每個字段 let catalogueField = fileItem.webkitRelativePath.split('/'); //要執(zhí)行的js語句拼接 let objStr = catalogueField.reduce((pre, cur, index, arr) => { /** * pre:上一次調(diào)用返回的值,或者提供的初始值 * cur:數(shù)組中當前處理的元素 * index:數(shù)組中當前處理的元素的下標 * arr:調(diào)用reduce函數(shù)的數(shù)組 * */ if (index >= arr.length - 1) { !eval(pre) && (eval(`${pre}={isLeaf:true}`)) pre = `${pre}['${fileData.noTypeName}']`; } else { index == 0 ? pre = `${pre}['${cur}']` : pre = `${pre}.Folder['${cur}']`; !eval(pre) && (eval(`${pre}={isLeaf:false,type:'folder',Folder:{}}`)) } // !eval(pre) && (eval(`${pre}={isLeaf:false}`)) return pre; }, 'catalogue'); eval(`${objStr}={isLeaf:true,...${fileData_}}`); }; return catalogue; } } //寫成json文件輸出 function saveToJson(data) { if (!data) { console.error("json文件的數(shù)據(jù)對象不存在"); return; } /** * JSON.stringify(value[, replacer [, space]]) * * value:將要序列化成 一個 JSON 字符串的值。 * * replacer * 如果該參數(shù)是一個函數(shù),則在序列化過程中,被序列化的值的每個屬性都會經(jīng)過該函數(shù)的轉(zhuǎn)換和處理; * 如果該參數(shù)是一個數(shù)組,則只有包含在這個數(shù)組中的屬性名才會被序列化到最終的 JSON 字符串中; * 如果該參數(shù)為 null 或者未提供,則對象所有的屬性都會被序列化。 * * space * 指定縮進用的空白字符串,用于美化輸出(pretty-print); * 如果參數(shù)是個數(shù)字,它代表有多少的空格;上限為 10。該值若小于 1,則意味著沒有空格; * 如果該參數(shù)為字符串(當字符串長度超過 10 個字母,取其前 10 個字母),該字符串將被作為空格; * 如果該參數(shù)沒有提供(或者為 null),將沒有空格。 * */ var content = JSON.stringify(data, null, '\t'); // 轉(zhuǎn)成blob數(shù)據(jù)對象 var blob = new Blob([content], { type: "text/plain;charset=utf-8" }); //第二步 => 文件數(shù)據(jù) 轉(zhuǎn)為可以 下載 的地址路徑 改路徑指向文件數(shù)據(jù) /** * objectURL = URL.createObjectURL(object); * * object:用于創(chuàng)建 URL 的 File 對象、Blob 對象或者 MediaSource 對象。 * 返回值:一個DOMString包含了一個對象 URL,該 URL 可用于指定源 object的內(nèi)容。 * * 在每次調(diào)用 createObjectURL() 方法時,都會創(chuàng)建一個新的 URL 對象, * 即使你已經(jīng)用相同的對象作為參數(shù)創(chuàng)建過。當不再需要這些 URL 對象時,每個對象必須通過調(diào)用 URL.revokeObjectURL() 方法來釋放。 * * * 與FileReader.readAsDataURL(file)區(qū)別 * 主要區(qū)別 * 通過FileReader.readAsDataURL(file)可以獲取一段data:base64的字符串 * 通過URL.createObjectURL(blob)可以獲取當前文件的一個內(nèi)存URL * * 執(zhí)行時機 * createObjectURL是同步執(zhí)行(立即的) * FileReader.readAsDataURL是異步執(zhí)行(過一段時間) * * 內(nèi)存使用 * createObjectURL返回一段帶hash的url,并且一直存儲在內(nèi)存中,直到document觸發(fā)了unload事件(例如:document close)或者執(zhí)行revokeObjectURL來釋放。 * FileReader.readAsDataURL則返回包含很多字符的base64,并會比blob url消耗更多內(nèi)存,但是在不用的時候會自動從內(nèi)存中清除(通過垃圾回收機制) * * 優(yōu)劣對比 * 使用createObjectURL可以節(jié)省性能并更快速,只不過需要在不使用的情況下手動釋放內(nèi)存 * 如果不太在意設備性能問題,并想獲取圖片的base64,則推薦使用FileReader.readAsDataURL * */ let url = window.URL.createObjectURL(blob); //這里你會看到類似的地址:blob:http://localhost:8080/d2dbbe3f-7466-415b-a2d0-387cff290acb console.log(url); //動態(tài)創(chuàng)建a標簽 => 模擬觸發(fā)a標簽的下載 => 用于將生成的json數(shù)據(jù)下載到本地 let link = document.createElement('a'); link.style.display = "none"; link.href = url; link.setAttribute('download', 'model.json'); document.body.appendChild(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(url); } /* 文件輸出 */ function outputFile(files) { filesData = ''; btnDisabled(saveJsonBtn); handleFiles(files).then(res => { filesData = res; btnCanClick(saveJsonBtn) obj.innerText = JSON.stringify(res, null, 2); }).catch(err => { console.error(err) }) } /* 按鈕可選 */ function btnCanClick(btnObj) { btnObj.removeAttribute('disabled'); } /* 按鈕不可選 */ function btnDisabled(btnObj) { btnObj.setAttribute('disabled', 'disabled'); } </script> </body> </html>
以上就是“Js怎么根據(jù)文件夾目錄獲取Json數(shù)據(jù)輸出demo”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關(guān)注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。