美文网首页
上传接口返回的是数据流如何处理

上传接口返回的是数据流如何处理

作者: 14px | 来源:发表于2021-11-20 03:01 被阅读0次

入参是 json,返回的是 blob

<template>
    <el-button @click="handleExport" type="primary">导出 Excel</el-button>
</template>
<script>
methods: {
                // 导出excel
        async handleExport() {
            const params = {
                              a:'a',
                              b:'b'
                        }
            const url = 'xxx/xxx'
            let res = await this.uploadFileRequest(url, params);
            if (res.status === 200) {
                const content = res.data;
                const blob = new Blob([content]);
                const fileName = `xxx.xls`;
                const elink = document.createElement('a');
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href);
                document.body.removeChild(elink);
            } else {
                this.$message('文件导出失败,请重试');
            }
        },
        uploadFileRequest(url, params) {
            return axios({
                method: 'post',
                url: url,
                data: params,
                responseType: 'blob',
            });
        },
}
</script>

特别要注意的地方是

  1. 不能用 axios.post 这样的方式,否则无法设置 responseType: 'blob',不然返回的就是一陀乱码,res.data 一定要是个 blob 才是正确的。
  2. 文件名的后缀,一定要和后台约定的是一致的,否则 wps 可以打开,excel 打不开。

入参是 file,返回的是 blob

上传必然要用上传组件,然而坑爹的是,elementui 的上传组件只能接受 json 的返回值。
所以很简单,不用 el-upload 就可以了。

<template>
<i class="el-icon-circle-plus-outline" @click="$refs.fileUpload.click()">excel导入</i>
<input type="file" v-show="false" ref="fileUpload" accept=".xlsx,.xls" @change="importFile($event)" />
</template>
<script>
methods: {
    importFile(e) {
        let sendFile = new FormData();
        sendFile.append('file', e.target.files[0]);
        axios({
            method: 'post',
            url: 'xxx/xxx',
            data: sendFile,
            responseType: 'blob',
        }).then((res) => {
            this.resexcel = res.data;
        });
    }
}
</script>

拿到 excel 之后,就请自便吧。

相关文章

网友评论

      本文标题:上传接口返回的是数据流如何处理

      本文链接:https://www.haomeiwen.com/subject/unlytrtx.html