Vue中携带请求头(token)的上传与下载

(1)先说上传的,我这里是上传的xlsx文件:
Html代码:


Js代码:

uploads(e) {
    // 获取到当前文件对象
    const file = e.target.files[0]
    // 传递一个FormData对象即可
    const formData = new FormData()
    formData.append('file', file) // 'file'可变相当于input表单的name属性
    // 服务器只需按照正常的上传程序代码即可
    axios.post(this.uploadUrl, formData, {
	    xsrfHeaderName: 'Authorization', // 请求头的名字自定义,用你们后台给你的就是
	    headers: {
		    'Content-Type': 'multipart/form-data',
		    'Authorization': 'Bearer ' + getToken() // 请求头的规则,用你们后台给你的就是
    }
    }).then(res => {
	    console.log(res)
	    if (res.data.result === '200') {
		    this.$message.success('上传成功')
		    this.isShowTips = true
	    } else {
	    	this.$message.error('哎呀~上传失败')
	    }
    }).catch(err => {
	    console.error(err)
	    this.$message.error('哎呀~上传失败,请稍后重试')
    })
},

(2)再说下载,我这里也是下载的xlsx文件:
Html代码(表格后面的操作按钮):


    

js代码

// 下载
doDownLoad(index, row) {
    console.log(index, row)
    axios.get('http://xxxxxxxxx/gs/file/export?id=' + row.id, {
	    responseType: 'arraybuffer', // 或者responseType: 'blob'
	    xsrfHeaderName: 'Authorization',
	    headers: {
		    'Content-Type': 'application/json',
		    'Authorization': 'Bearer ' + getToken()
	    }
    }).then(res => {
	    const blob = new Blob([res.data], {
		    type: 'application/vnd.ms-excel'
	    })
	    const objectUrl = URL.createObjectURL(blob)
	    window.location.href = objectUrl
    }).catch(err => {
    	console.log(err)
    })
}

你可能感兴趣的:(技术博客)