詳解Js 根據(jù)文件夾目錄獲取Json數(shù)據(jù)輸出demo
更新時間:2023年03月28日 09:55:15 作者:surly
這篇文章主要為大家介紹了Js 根據(jù)文件夾目錄獲取Json數(shù)據(jù)輸出示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
1.搭建初始樣式(html,css)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
h2 {
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>
<h2>文件夾路徑生成json文件</h2>
<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ù)預(yù)覽</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>
2.文件夾目錄轉(zhuǎn)換成JSON數(shù)據(jù)
//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ù)組中當(dāng)前處理的元素
* index:數(shù)組中當(dāng)前處理的元素的下標(biāo)
* 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;
}
}
3.JSON數(shù)據(jù)輸出成JSON文件
//寫成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標(biāo)簽 => 模擬觸發(fā)a標(biāo)簽的下載 => 用于將生成的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);
}
4.完整代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
h2 {
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>
<h2>文件夾路徑生成json文件</h2>
<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ù)預(yù)覽</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標(biāo)簽的點擊
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ù)組中當(dāng)前處理的元素
* index:數(shù)組中當(dāng)前處理的元素的下標(biāo)
* 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
* 指定縮進(jìn)用的空白字符串,用于美化輸出(pretty-print);
* 如果參數(shù)是個數(shù)字,它代表有多少的空格;上限為 10。該值若小于 1,則意味著沒有空格;
* 如果該參數(shù)為字符串(當(dāng)字符串長度超過 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)建過。當(dāng)不再需要這些 URL 對象時,每個對象必須通過調(diào)用 URL.revokeObjectURL() 方法來釋放。
*
*
* 與FileReader.readAsDataURL(file)區(qū)別
* 主要區(qū)別
* 通過FileReader.readAsDataURL(file)可以獲取一段data:base64的字符串
* 通過URL.createObjectURL(blob)可以獲取當(dāng)前文件的一個內(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)存
* 如果不太在意設(shè)備性能問題,并想獲取圖片的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標(biāo)簽 => 模擬觸發(fā)a標(biāo)簽的下載 => 用于將生成的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>
預(yù)覽

以上就是詳解Js 根據(jù)文件夾目錄獲取Json數(shù)據(jù)輸出demo的詳細(xì)內(nèi)容,更多關(guān)于Js獲取Json數(shù)據(jù)輸出的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
JavaScript時間轉(zhuǎn)換處理函數(shù)
這篇文章主要介紹了JavaScript時間轉(zhuǎn)換處理函數(shù)的方法的相關(guān)資料,需要的朋友可以參考下2015-04-04
基于邏輯運算的簡單權(quán)限系統(tǒng)(實現(xiàn)) JS 版
基于邏輯運算的簡單權(quán)限系統(tǒng)(實現(xiàn)) JS 版...2007-03-03
javascript實現(xiàn)瀑布流自適應(yīng)遇到的問題及解決方案
這篇文章主要介紹了javascript實現(xiàn)瀑布流自適應(yīng)遇到的問題及解決方案,需要的朋友可以參考下2015-01-01
JavaScript實現(xiàn)一個多少秒后自動跳轉(zhuǎn)的頁面(案例代碼)
最近遇到這樣一個需求是用js簡單實現(xiàn)一個多少秒后自動跳轉(zhuǎn)的頁面,實現(xiàn)代碼非常簡單,對js自動跳轉(zhuǎn)頁面相關(guān)知識感興趣的朋友一起看看吧2023-01-01
js面向?qū)ο蠓庋b級聯(lián)下拉菜單列表的實現(xiàn)步驟
這篇文章主要介紹了js面向?qū)ο蠓庋b級聯(lián)下拉菜單列表的實現(xiàn)步驟,幫助大家更好的理解和使用JavaScript,感興趣的朋友可以了解下2021-02-02

