文件上传&下载

  1. 文件上传
// js调用
var input = document.createElement('input')
input.id = 'template-upload'
 input.type = 'file'
 input.click()
 input.onchange = () => {
   var file = input.files[0]
   var form = new FormData()
   form.append('file', file) // 第一个参数是后台读取的请求key值
   // form.append('fileName', file.name)
   templateUpload(form).then(res => {
     this.$message.success(res)
   }).catch(error => {
     this.$message.error(error)
   })
 }

// 接口
export const templateUpload = (data) => {
  return fetch({
    url: '',
    method: 'post',
    data
  })
}
  1. 文件下载
// js调用
templateDownLoad().then(res => {
   const fileName = 'xxx.xlsx'
   const blob = new Blob([res], {
     type: 'application/vnd.ms-excel;charset=utf-8'
   })
   if (navigator.msSaveBlob) {
     navigator.msSaveBlob(blob, fileName)
   } else {
     const link = document.createElement('a')
     link.href = URL.createObjectURL(blob)
     link.download = fileName
     link.click()
     URL.revokeObjectURL(link.href)
   }
 })

// 接口
export const templateDownLoad = () => {
  return fetch({
    url: '',
    method: 'get',
    responseType: 'blob'
  })
}

你可能感兴趣的:(前端,前端)