• Vue项目文件导入、导出


    Vue项目中文件导入和导出使用比较频繁,这里把最常用的布局和实现代码记录下来,避免以后频繁造轮子。

    1、导出一般就是在列表中选择几条数据,然后点击导出按钮把选中的数据下载下来;导入的话一般会有一个单独的弹框页面,需要先选择文件,然后统一导入。

    导入弹框 

    2、导入弹框对应的页面代码:

    1. <template>
    2. <el-dialog
    3. title="导入"
    4. :visible.sync="dialogVisible"
    5. width="660px"
    6. :close-on-click-modal="false"
    7. :before-close="onClose"
    8. @closed="onAfterClose"
    9. >
    10. <div
    11. v-loading="loading"
    12. class="dialog-content"
    13. >
    14. <el-form
    15. ref="formRef"
    16. :model="formData"
    17. label-width="80px"
    18. >
    19. <el-form-item
    20. label="选择文件"
    21. prop="fileList"
    22. >
    23. <el-upload
    24. ref="upload"
    25. action="#"
    26. :accept="extAcceptStr"
    27. :auto-upload="false"
    28. :limit="limit"
    29. :file-list="formData.fileList"
    30. :on-change="onFileChange"
    31. :on-remove="onFileMove"
    32. :on-exceed="onFileExceed"
    33. >
    34. <div class="select-file">
    35. <p class="select-p">
    36. 请选择上传文件
    37. p>
    38. <el-button
    39. size="small"
    40. type="primary"
    41. >
    42. 选取文件
    43. el-button>
    44. div>
    45. <div
    46. slot="tip"
    47. class="el-upload__tip"
    48. >
    49. {{ `支持${extAcceptStr}格式的文件,大小不能超过10M` }}
    50. div>
    51. el-upload>
    52. <el-button
    53. type="text"
    54. @click="onDownload"
    55. >
    56. 模板下载
    57. el-button>
    58. el-form-item>
    59. el-form>
    60. div>
    61. <template slot="footer">
    62. <el-button
    63. type="primary"
    64. :loading="!!loading"
    65. :disabled="!formData.fileList.length > 0"
    66. @click="onSubmit"
    67. >
    68. 导入
    69. el-button>
    70. <el-button @click="dialogVisible = false">
    71. 取消
    72. el-button>
    73. template>
    74. el-dialog>
    75. template>
    76. <script>
    77. export default {
    78. props: {
    79. loading: Boolean,
    80. limit: { //限制文件上传个数
    81. type: Number,
    82. default: 1,
    83. },
    84. },
    85. data () {
    86. return {
    87. // # config
    88. extAccept: ["xls", "xlsx"],
    89. // # state
    90. dialogVisible: false,
    91. // # data
    92. formData: {
    93. fileList: [],
    94. },
    95. }
    96. },
    97. computed: {
    98. extAcceptStr () {
    99. return this.extAccept.map(ext => `.${ext}`).join(",")
    100. },
    101. },
    102. methods: {
    103. onShow () {
    104. this.dialogVisible = true
    105. },
    106. onClose () {
    107. this.dialogVisible = false
    108. },
    109. onAfterClose () {
    110. this.formData = {
    111. fileList: [],
    112. }
    113. },
    114. // # upload
    115. // 校验
    116. validateFile (file) {
    117. if (!file) return "至少添加一个文件!"
    118. const ext = (file.name || "").split(".").reverse()[0]
    119. if (!this.extAccept.includes(ext))
    120. return `仅支持${this.extAcceptStr}格式的文件`
    121. return ""
    122. },
    123. onFileChange (file, fileList) {
    124. const errMsg = this.validateFile(file)
    125. if (errMsg) {
    126. this.$message.warning(errMsg)
    127. this.formData.fileList.splice(0, 1)
    128. } else {
    129. this.formData.fileList = fileList
    130. }
    131. },
    132. onFileMove (file, fileList) {
    133. this.formData.fileList = fileList
    134. },
    135. onFileExceed () {
    136. this.$message.warning(`仅允许上传 ${this.limit} 个文件!`)
    137. },
    138. // # emit
    139. // 模板下载
    140. onDownload () {
    141. this.$emit("download")
    142. },
    143. // 导入
    144. onSubmit () {
    145. this.$emit("submit", this.formData)
    146. },
    147. },
    148. }
    149. script>
    150. <style lang="less" scope>
    151. .dialog-content {
    152. height: 300px;
    153. padding: 16px;
    154. .select-file {
    155. display: flex;
    156. height: 36px;
    157. .select-p {
    158. width: 380px;
    159. height: 32px;
    160. line-height: 32px;
    161. border: 1px solid #dcdfe6;
    162. text-align: left;
    163. padding-left: 8px;
    164. color: #636fa1;
    165. font-size: 12px;
    166. }
    167. }
    168. }
    169. style>

     3、在父布局中使用弹框组件:

    ①导入

    ②布局中使用 

    1. <dialog-import
    2. ref="dialogImportRef"
    3. :loading="importLoading"
    4. @download="onTempDownload"
    5. @submit="onImportSubmit"
    6. />

     ③子组件对应的方法

    -----------------------------------------------  模板下载相关  -------------------------------------------

    1. //模板下载
    2. onTempDownload () {
    3. inlivePersonApi.downloadTemplate('1').then(res => {
    4. console.log(res)
    5. saveBlobToFile(res)
    6. })
    7. }
    1. // 下载人员导入修改模板
    2. downloadTemplate: (templateKey) => http.getBlob(`/v1/apartment/user/downloadTemplate?templateKey=${templateKey}`)

    saveBlobToFile是在公共方法中封装的下载方法:

    1. export function saveBlobToFile (res, filename) {
    2. if (res.headers['content-disposition']) {
    3. var fileName = decodeURIComponent(res.headers['content-disposition'].replace('attachment;filename=', ''))
    4. fileName = decodeURIComponent(fileName)
    5. var blob = res.data
    6. // var blob = new Blob([res.data], {
    7. // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    8. // })
    9. if (navigator.msSaveBlob) {
    10. navigator.msSaveBlob(blob, fileName)
    11. } else {
    12. const oA = document.createElement('a')
    13. try {
    14. oA.href = URL.createObjectURL(blob)
    15. } catch (err) {
    16. const binaryData = []
    17. binaryData.push(blob)
    18. oA.href = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/zip' }))
    19. }
    20. oA.download = filename || fileName
    21. oA.click()
    22. }
    23. }
    24. }

    -----------------------------------------------  导入相关  -------------------------------------------

    1. async onImportSubmit ({ fileList }) {
    2. this.importLoading = true
    3. let fd = new FormData()
    4. fd.append('excelFile', fileList[0].raw)
    5. inlivePersonApi.importExcel(fd).then(res => {
    6. this.importLoading = false
    7. if (res.success) {
    8. this.$refs.dialogImportRef.onClose()
    9. this.pageParams.pageNo = 1
    10. this.requestTableData()
    11. this.$message({
    12. message: '导入成功',
    13. type: 'success'
    14. })
    15. }
    16. })
    17. }
    1. // 人员导入
    2. importExcel: params => http.post('/v1/apartment/user/importExcel', params)

    4、导出业务其实和上面的模板下载业务一样,也是通过接口获取数据,然后通过文件形式下载下来。

  • 相关阅读:
    Java基础 | Stream流原理与用法总结
    flutter学习之widget的显示和隐藏
    Vue组件的继承用法
    leetcode-54. 螺旋矩阵
    JavaScript期末大作业 基于HTML+CSS+JavaScript技术制作web前端开发个人博客(48页)
    DNS域名解析服务
    618过后,该如何做视频号?
    【SQL注入】(1)原理,框架
    Spring简介
    idea 全局maven 设置
  • 原文地址:https://blog.csdn.net/ljw124213/article/details/126603397