使用 axios 上传和下载文件

文章目录

1. 上传

修改请求头

export function importFile (param) {
  const config = {
    // 添加请求头
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }
  return axios.post('/importFile', param, config)
}

获取文件,用formData包装,调用接口

const element = document.getElementById('fileToUpload')
const files = element.files
const formData = new FormData()
const file = element.files[0]
formData.append('file', file)
importFile (formData).then(res => {
// ...
})

2. 下载

export function downloadFile (param) {
  return axios.post('/downloadFile ',
    qs.stringify(param, { indices: false }),
    {
      responseType: 'arraybuffer'
    }
  )
}
exportInfoResource(param).then(res => {
  _this.handleExcelExportResult(res)
})

handleExcelExportResult (res) {
	const blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' })
	const downloadLink = document.createElement('a')
	// 创建下载的链接
	const href = window.URL.createObjectURL(blob)
	downloadLink.href = href
	// 下载后文件名, 返回res中只有二进制数据,获取不到header
	// const disposition = res.headers['content-disposition']
	// downloadLink.download = decodeURI(disposition.substring(disposition.indexOf('filename=') + 9, disposition.length))
	downloadLink.download = moment(new Date()).format('YYYYMMDDhhmmss') + '.xls'
	document.body.appendChild(downloadLink)
	downloadLink.click()
	document.body.removeChild(downloadLink)
	// 释放掉blob对象
	window.URL.revokeObjectURL(href)
},

参考:
使用axios上传文件、下载(导出)文件

发布了65 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36160730/article/details/103071127