vue小工具 - 单文件上传

106 阅读1分钟

背景介绍

在项目中有很多地方需要用到文件上传,但是很多时候都是单个的文件,用 el-upload 写起单个文件上传来
太过重度了

设想

如果我只用写一个 button 就能模拟文件的上传,体验会很顺滑

<el-button @click="() => {
	_importFile(接口名称, res => {
        if (res.code === '1') {
          $message.success('上传成功')
          
          // 重新获取数据
          getData()
          
        } else {
          $message.error('上传失败')
        }
      })
}"> 上传文件 </el-button>

在方法中修改 type 设置FormData中的名字,accept属性设置允许什么上传...
大家可以自行拓展,让方法更符合自己的习惯需求

// main.js

// 单个文件下载
Vue.prototype._importFile = (callback, then) => {
  const params = new FormData()
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xls,.xlsx'

  input.addEventListener('change', function(e) {
    const file = e.target.files[0]
    if (file) {
      params.append('file', file)
      callback(params)
        .then(res => {
          then(res)
        })
    }
  })
  input.click()
}