导入
示例如图:
后端接收的文件类型为文件流,这里就需要用到js的FormData接口,具体参考new FormData()
前端构造参数代码:
const formData = new FormData();
formData.append('docFile', file); // file为上传的文件
formData.append('otherParams', otherParams); // 继续以append方式加入其他参数
httpImport(formData) // 以formData为接口请求所需参数调接口实现导入功能
使用element ui 的el-upload组件上传文件流
视图部分:
<el-dialog title="导入" :visible.sync="dialogVisible" width="30%">
<el-upload
ref="upload"
action="#"
accept=".xls,.xlsx"
:auto-upload="false"
:multiple="false"
:http-request="importHttpRequest"
:file-list="fileList"
:on-change="fileChange"
:show-file-list="true"
>
<el-button type="text">选择文件导入</el-button>
<div slot="tip" class="el-upload__tip">一次只能上传一个xls/xlsx文件</div>
</el-upload>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="handleSubmitImport">确 定</el-button>
</span>
</el-dialog>
js部分:
// 导入
importHttpRequest (params) {
const formData = new FormData()
formData.append('file', params.file)
formData.append('otherParams', this.otherParams) // 加其他 接口需求的 参数
httpImportData(formData).then(res => {
this.$message({
type: 'success',
message: '导入成功'
})
this.dialogVisible = false
this.fileList = []
})
},
handleSubmitImport () {
this.$refs.upload.submit()
}
导出
基本代码如下:
this.$axios({
method: 'post',
url,
headers: { Authorization: Cookies.get('token') },
responseType: 'arraybuffer', // 这个参数要加
data
}).then(res => {
const fileName = decodeURIComponent(
res.response.headers
.get('Content-Disposition')
.split("filename*=utf-8''")[1]
);
const url = window.URL.createObjectURL(new Blob([res.data]), {
type: res.response.headers.get('Content-Type'),
});
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})