vue3 文件导入导出

303 阅读1分钟

后端接口部分就不多数了,下面贴出前端代码~~~


html 添加一个导入/导出按钮

<a-button type="primary" @click="onImport(record)">导入</a-button>
<a-button type="primary" @click="onExport(record)">导出</a-button>

js 导入/导出

import { saveAs } from 'file-saver'
import { ref, reactive, getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()


/**
 * 导入
 * @param {*} record
 */
const onImport = async record => {
  try {
    const arrFile = await window.showOpenFilePicker({
      types: [
        {
          accept: {
            'text/plain': ['.txt']
          }
        }
      ]
    })
    if (!arrFile || !arrFile.length) {
      return
    }
    const file = arrFile[0]
    const fileData = await file.getFile()
    const content = await fileData.text()
    const processContent = JSON.parse(content)
    await ImportMailTemplate({ templateContent: processContent })
    proxy.$message.success('导入成功')
  } catch (error) {
    console.error(error)
  }
}

/**
 * 导出
 * @param {*} record
 */
const onExport = async record => {
  try {
    const { data } = await ExportMailTemplate({ id: record.id }) // 获取要导出内容
    const file = JSON.stringify(data.templateContent)
    const blob = new Blob([file], { type: 'text/plain;charset=utf-8' })
    saveAs(blob, `${record.name}_v${record.version}.txt`)
    proxy.$message.success('导出成功')
  } catch (error) {
    console.error(error)
  }
}

结束。