前端下載文件時(shí)先打開系統(tǒng)文件目錄,把文件下載到選擇的指定目錄
功能實(shí)現(xiàn)關(guān)鍵Api showSaveFilePicker 可以打開文件目錄之后返回文件對(duì)象對(duì)文件進(jìn)行讀寫操作,類似node fs的文件讀寫,但是這個(gè)Api兼容性有些問題如下。如果只考慮window 10,11系統(tǒng)用戶還是可以用一下的。
文章來源:http://www.zghlxwxcb.cn/news/detail-697971.html
以下是.docx文件的例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>另存為</title>
</head>
<body>
<button id="button">另存為</button>
</body>
<script>
// 加載文件
const loadingFile = (path = '') => {
const params = {
headers: { 'Content-Type': 'application/json' },
responseType: 'blob'
}
return fetch(path, params)
}
// MIME類型
const MIME_MAP = new Map([
['.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
])
// blob轉(zhuǎn)ArrayBuffer
const blobToArrayBuffer = (blob) => {
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.addEventListener('load', () => resolve(reader.result))
reader.addEventListener('error', () => reject(`文件轉(zhuǎn)化失?。?/span>`))
reader.readAsArrayBuffer(blob)
})
}
// 文件地址
const filePath = `http://localhost:5500/1.docx`
window.addEventListener('load', () => {
const button = document.querySelector('#button')
button.addEventListener('click', () => {
loadingFile(filePath)
.then((response) => {
// 取出文件
return response.blob()
}).then((blob) => {
// 類型轉(zhuǎn)化
return blobToArrayBuffer(blob)
}).then(async (buffer) => {
const fileType = '.docx'
const options = {
// 默認(rèn)另存文件名
suggestedName: '測試文件',
types: [
{
description: 'docx',
accept: { [MIME_MAP.get(fileType)]: [fileType] }
}
]
}
const fileHandle = await showSaveFilePicker(options)
const writable = await fileHandle.createWritable()
await writable.write(buffer)
await writable.close()
}).catch((error) => {
console.log(error)
})
})
})
</script>
</html>
如果有更好的建議歡迎回復(fù)~文章來源地址http://www.zghlxwxcb.cn/news/detail-697971.html
到了這里,關(guān)于前端文件選擇目錄另存為的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!