上传表格后下载表格,异步下载文件 CJayhe 技术分享 277 views ## 原生写法 ```html <!DOCTYPE html> <html> <head> <title>Excel 文件上传和下载</title> <script> function uploadFile() { var fileInput = document.getElementById("excelFile"); var file = fileInput.files[0]; var formData = new FormData(); formData.append("file", file); var xhr = new XMLHttpRequest(); xhr.open("POST", "接口地址", true); xhr.responseType = "blob"; xhr.onload = function () { if (xhr.status === 200) { // 创建一个虚拟的下载链接并自动点击下载 var downloadLink = document.createElement("a"); var blob = new Blob([xhr.response], { type: "application/vnd.ms-excel" }); var url = URL.createObjectURL(blob); downloadLink.href = url; downloadLink.download = "output.xls"; downloadLink.click(); } }; xhr.send(formData); } </script> </head> <body> <h1>Excel 文件上传和下载</h1> <input type="file" id="excelFile" accept=".xls, .xlsx"> <button onclick="uploadFile()">上传</button> </body> </html> ``` ## vue写法 el-upload ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Excel 文件上传和下载</title> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> </head> <body> <div id="app"> <h1>Excel 文件上传和下载</h1> <el-upload ref="upload" class="upload-demo" action="接口地址" :auto-upload="false" :on-change="handleFileChange" :file-list="fileList" > <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <div slot="tip" class="el-upload__tip">只能上传 xls/xlsx 格式的文件</div> </el-upload> <el-button @click="submitUpload" type="primary">上传</el-button> </div> <script src="{{ asset('bundles/phpzlcadmin/vue/vue.js') }}"></script> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> new Vue({ el: '#app', data() { return { fileList: [] } }, methods: { handleFileChange(file, fileList) { this.fileList = fileList; }, submitUpload() { const formData = new FormData(); console.log(this.fileList) formData.append('file', this.fileList[0].raw); var xhr = new XMLHttpRequest(); xhr.open("POST", "接口地址", true); xhr.responseType = "blob"; xhr.onload = function () { if (xhr.status === 200) { const contentType = xhr.getResponseHeader('Content-Type'); if (contentType.indexOf('application/json') !== -1) { xhr.response.text().then((text) => { const data = JSON.parse(text); console.log(data) }); }else{ // 创建一个虚拟的下载链接并自动点击下载 var downloadLink = document.createElement("a"); var blob = new Blob([xhr.response], { type: "application/vnd.ms-excel" }); var url = URL.createObjectURL(blob); downloadLink.href = url; downloadLink.download = "output.xls"; downloadLink.click(); } } }; xhr.send(formData); } } }); </script> </body> </html> ``` 乱码问题的核心在于 `responseType = "blob";` ;如果不设置,文件会下载不完整,故而乱码。`el-upload` 组件不支持设置,故而需要重写。 帮助PHPZlc项目! 与任何开源项目一样, 贡献代码 或 文档 是最常见的帮助方式, 但我们也有广泛的 赞助机会。 0 赞赏 加入技术群 评论 去登录