最近在做项目的时候,有一个批量上传内容的需求,上传的是一个excel文档。返回值也是一个Excel文档。
我这边之前的做法是直接搞个表单,把相关的字段填好,发送就可以了。
但是其实这是从一个弹窗里面submit的,使用表单的话,就监控不到上传的进度,也就不知道啥时候关闭弹窗,于是产品就问了,这个怎么解决呀,我是等了三秒后直接关闭,但是这样子感觉很low,就想能不能通过ajax来做呢,下面是表单的写法
<form ref="uploadForm" :action="actionUrl" method="post" enctype="multipart/form-data" v-if="operator"> <label for="upfile" class="pTitleRight"> <span>Content</span> <el-button type="primary" @click="clickHandle">Upload File</el-button> <span>{{fileName}}</span> <input ref="filElem" type="file" id="upfile" name="file" style="display: none;" @change="upload" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" /> </label> <input type="text" name="zone" value="sa" hidden> <input type="text" name="operator" :value="operator.name" hidden> <input type="text" name="userId" :value="operator.id" hidden> </form>
下面是ajax的写法了,
重要的是需要设置返回的类型,选择blob,这样就可以构造a标签来自动下载了。
submit() { this.loading = true; const formData = new FormData(); formData.append('file', this.file); formData.append('zone', 'sa'); formData.append('operator', this.operator.name); formData.append('userId', this.operator.id); const config = { headers: { 'Content-Type': 'multipart/form-data', }, withCredentials: true, responseType: 'blob', }; const fileName = 'import_sbcms_result'; axios.post(this.actionUrl, formData, config).then((res) => { this.loading = false; this.close(); this.$emit('addSuccess'); this.$refs.filElem.value = ''; const blob = res.data; // 如果size小于100,一般是报错了 if (blob.size < 100) { const reader = new FileReader(); reader.readAsText(res.data, 'utf-8'); reader.onload = (e) => { this.$message({ showClose: true, message: JSON.parse(e.target.result).message, type: 'error', }); }; return; } if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveBlob(blob, fileName); } else { const downloadLink = window.document.createElement('a'); // const contentTypeHeader = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; const contentTypeHeader = res.headers['content-type']; downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader })); downloadLink.download = fileName; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } }).catch((e) => { this.$message.error(e); });