vue項目通過Blob對象下載文件的方法(文件名中文轉成utf-8)以及使用fileReader來讀取文件


function exportFile(url, payload) {
const downloadBlob = (data, fileNameS) =>{
if (!data) {
return
}
let blob = new Blob([data], {type: "application/zip"})
let fileName = ${fileNameS}
///通過 使用a標簽的download方法下載文件
if ('download' in document.createElement('a')) {
// 靜態方法會創建一個 DOMString,其中包含一個表示參數中給出的對象的URL。
// 這個 URL 的生命周期和創建它的窗口中的 document 綁定。這個新的URL 對象表示指定的 File 對象或 Blob 對象
let url = window.URL.createObjectURL(blob)
let link = document.createElement('a')
link.href = url
link.style.display = 'none'
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link);
// 靜態方法用來釋放一個之前通過調用 URL.createObjectURL() 創建的已經存在的 URL 對象。
// 當你結束使用某個 URL 對象時,應該通過調用這個方法來讓瀏覽器知道不再需要保持這個文件的引用了。
window.URL.revokeObjectURL(url)
} else {
window.navigator.msSaveBlob(blob, fileName)
}
}
io.post(url, payload, res => {
// 第二個參數為下載的文明名稱
downloadBlob(res, payload.filename)
//讀取本地文件,以gbk編碼方式輸出
var reader = new FileReader();
reader.readAsText(res,"gbk");
reader.onload = function(){
//讀取完畢后輸出結果
console.log(reader.result);
}
}, e => {}, {
responseType: 'blob'
})
}

export {exportFile}

// 頁面的使用
import {exportFile} from 'file'
exportFile (url, {data})

data結構

參考文獻: https://blog.csdn.net/qq_40298902/article/details/121779944
https://blog.csdn.net/SunFlower914/article/details/123558341
http://t.zoukankan.com/dongxixi-p-11005607.html //用fileReader來讀取文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM