前端导入 和导出json文件

542 阅读1分钟

导出json文件:

index.vue
import { saveAs } from 'file-saver'
const doImportJson=()=>{

 const jsonBlob = new Blob([JSON.stringify(query)], {
          type: 'application/json',
        })
        saveAs(jsonBlob, `${feilName}.json`)

}

导入json文件:

//index.vue
 import { readFile } from '@/utils'
 
 const file = await readFile('.json')
        const reader = new FileReader()

        reader.onload = (event) => {
          const json = JSON.parse(event.target.result)
          console.log(json, 'json')
        }

        reader.readAsText(file)
//utils.js
/**
 * 调用 input file 选择框,读取一个或多个文件
 * @param {string} accept - 有效的文件后缀,多个后缀用','隔开。如('.xlsx,.docx')
 * @param {boolean} multiple - 是否读取多个文件
 * @returns {Promise<File | File[]>}
 */
export function readFile(accept = '', multiple = false) {
  const inputEl = document.createElement('input')
  inputEl.setAttribute('type', 'file')
  inputEl.setAttribute('accept', accept)
  inputEl.setAttribute('multiple', !!multiple)
  return new Promise((resolve, reject) => {
    inputEl.addEventListener('change', (e) => {
      resolve(multiple ? inputEl.files : inputEl.files[0])
      window.removeEventListener('click', onWindowClick, true)
    })
    inputEl.click()

    const onWindowClick = () => {
      if (!inputEl.value) {
        reject(new Error('用户取消选择'))
      }
      window.removeEventListener('click', onWindowClick, true)
    }
    setTimeout(() => {
      window.addEventListener('click', onWindowClick, true)
    }, 100)
  })
}