这是我参与8月更文挑战的第4天,活动详情查看:8月更文挑战
常用的下载/导出等工具类组件或者方法,可根据需求自行扩展。
导出(下载)
一般请求头添加responseType
,以流的形式传递
responseType:'blob',// 流 形式
导出excel常用封装
// 导出excel
export function downloadBlob(data, fileName) {
const link = document.createElement('a')
const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
// link.download = res.headers['content-disposition'] //下载后文件名
link.download = fileName // 下载的文件名
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
请求头信息:
返回信息:
导入组件使用:
<uploadFile :visible.sync="visibleFile" :on-success="fileSuccess" />
Api.xxx()
的请求头同样考虑添加 responseType:'blob',// 流 形式
// 导入上传
fileSuccess(data) {
const param = new FormData() // FormData 对象
param.append('file', data.raw) // 文件对象
// param.append('uploadTitle', name) // 其他参数
Api.xxx(param).then(res => {
this.visibleFile = false
console.log(res, res.type)
})
}
最后,附上uploadFile组件
<template>
<ComDialog
width="450px"
:title="fileTitle"
:visible="visible"
@before-close="handleClose"
>
<template>
<slot />
<el-form
ref="fileForm"
:model="fileForm"
:rules="rules"
label-width="80px"
class="form-ruleForm"
>
<el-form-item label="选择文件" prop="name">
<el-input v-model="fileForm.name" placeholder="请选择" readonly />
<el-upload
ref="upload"
class="upload-demo"
:action="'#'"
:show-file-list="false"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="handleAvatarSuccess"
:on-change="handleChange"
:before-upload="beforeAvatarUpload"
:auto-upload="false"
>
<el-button slot="trigger" type="primary">选取文件</el-button>
</el-upload>
</el-form-item>
</el-form>
</template>
<template slot="footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
</template>
</ComDialog>
</template>
<script>
import ComDialog from '@/components/ComDialog'
export default {
name: 'UploadFile',
components: { ComDialog },
props: {
fileTitle: {
type: String,
default: '文件上传'
},
visible: {
type: Boolean,
default: false
},
onSuccess: {
type: Function,
default: null
}
},
data() {
return {
rules: {},
fileForm: {
name: ''
}
}
},
methods: {
handleChange(data) {
this.fileForm = { ...data }
},
handleRemove(file, fileList) {
console.log(file, fileList)
},
handlePreview(file) {
console.log(file)
},
handleClose() {
this.fileForm = {
name: ''
}
this.$emit('update:visible', false)
},
handleAvatarSuccess(data) {
console.log(data)
},
beforeAvatarUpload(data) {
console.log(data)
},
submitForm() {
if (this.onSuccess) {
this.onSuccess(this.fileForm)
} else {
this.$emit('callback', this.fileForm)
}
}
}
}
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
display: flex;
.el-button {
margin-left: 16px;
}
}
</style>
期望
点个赞再走呗~~~