文件上传与下载

139 阅读1分钟

1.上传

export function importData (data) {
  return axios({
    url: '/scwc/import',
    method: 'post',
    data
  })
}

<el-upload
  ref="upload"
  accept=".png,.jpg,.jpeg"
  action=""
  :auto-upload="false"
  :file-list="fileList"
  :on-change="handleFileChange"
  :before-remove="handleFileRemove">
  <el-button type="primary" size="medium" slot="trigger">选择文件</el-button>
  <el-button
    type="success"
    size="medium"
    @click="submitUpload"
    style="margin-left:15px;"
    :disabled="!fileList.length"
    :loading="loading_upload">{{ loading_upload?'上传中':'上传' }}</el-button>
  <div slot="tip" class="el-upload__tip">只能上传.png,.jpg,.jpeg文件</div>
</el-upload>
data中: fileList:[]


handleFileChange(file, fileList) {
    this.fileList = fileList
},
handleFileRemove(file, fileList) {
    this.fileList = fileList
},
submitUpload() {
     const fromData = new FormData()
     fromData.append('files', file) //'files'为参数名,可以根据实际修改
     fromData.append('username', 'tom') //可以追加其它参数
     importData(fromData).then(res=>{})
}

特殊情况:用户导入的文件内容有问题时,后台返回含提示信息的文件流,前端自动下载

export function importData ( data) {
  return axios({
    url: `/scwc/import`,
    method: 'post',
    data,
    responseType: 'blob'
  })
}

submitUpload() {
     const fromData = new FormData()
     fromData.append('files', file) //'files'为参数名,可以根据实际修改
     fromData.append('username', 'tom') //可以追加其它参数
     importData(fromData).then(res=>{
        if (Object.prototype.toString.call(res.data) === '[object Blob]') {
          if (res.data.type.includes('application/json')) {
            const reader = new FileReader()
            reader.onload = () => {
                const result = JSON.parse(reader.result)
                if (result.code === 200) {
                    this.$message.success('导入成功')
                    this.dialogVisible_upload = false
                } else {
                  this.$message.error(result.message)
                }
            }
            reader.readAsText(res.data)
          } else {
            this.$message.error('导入数据格式错误,请检查')
            this.handleXlsRes(res)
          }
     })
},
handleXlsRes(res) {
  const blob = res.data
  const reader = new FileReader()
    reader.readAsDataURL(blob)
    reader.onload = e => {
      const link = window.document.createElement('a')
      const filename = res.headers['content-disposition'].split(';')[1].split('filename=')[1]
      const decodedFilename = decodeURIComponent(filename)
      link.download = decodedFilename + '.xlsx'
      link.href = e.target.result
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
},

2.下载

export function downloadTemplate () {
  return axios({
    url: '/yxSj/getImportTemplate',
    method: 'get',
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json; application/octet-stream'
    }
  })
}
法1(下载压缩包):
downloadTemplate().then(res => {
  const blob = new Blob([res.data], { type: 'application/zip' }) // 设置下载的内容以及格式
  const url = window.URL.createObjectURL(blob) // 设置路径
  const link = window.document.createElement('a')
  link.href = url
  const filename = res.headers['content-disposition'].split(';')[1].split('filename=')[1]
  const decodedFilename = decodeURIComponent(filename) // 解码文件名
  link.download = decodedFilename // 设置文件名
  link.style.display = 'none'
  link.click()
  URL.revokeObjectURL(url)
})

法2(下载xls文件):
downloadTemplate().then(res => {
  const blob = res.data
  const reader = new FileReader()
  reader.readAsDataURL(blob)
  reader.onload = e => {
    const link = window.document.createElement('a')
    const filename = res.headers['content-disposition'].split(';')[1].split('filename=')[1]
    const decodedFilename = decodeURIComponent(filename) // 解码文件名
    link.download = decodedFilename + '.xlsx'
    link.href = e.target.result
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
})