后台给的文件流GET请求并添加请求头下载文件 【文件流下载 添加请求头 GET请求 下载文件】

方法一

const token= window.sessionStorage.getItem('access_token');//如果有

function downLoadByUrl(url){
        var xhr = new XMLHttpRequest();
        //GET请求,请求路径url,async(是否异步)
        xhr.open('GET', url, true);
        //设置请求头参数的方式,如果没有可忽略此行代码
        xhr.setRequestHeader("authorization", token);
        //设置响应类型为 blob
        xhr.responseType = 'blob';
        //关键部分
        xhr.onload = function (e) {
            //如果请求执行成功
            if (this.status == 200) {
                var blob = this.response;
                var filename = "我是文件名";//如123.xls
                var a = document.createElement('a');
                blob.type = "application/octet-stream";
                //创键临时url对象
                var url = URL.createObjectURL(blob);
                a.href = url;
                a.download=filename;
                a.click();
                //释放之前创建的URL对象
                window.URL.revokeObjectURL(url);
            }
        };
        //发送请求
        xhr.send();
}

方法二

url是请求接口地址
handleDownLoad(url);


function handleDownLoad(url) {
    fetch(url, {
      method: 'GET',
      headers: new Headers({
        'authorization': window.sessionStorage.getItem('access_token')
      }),
    })
	.then(res => res.blob())
	.then(data => {
		const blobUrl = window.URL.createObjectURL(data);
		download(blobUrl);
	});
}

//模拟a标签实现下载excel文件
function download(blobUrl) {
	const a = document.createElement('a');
	a.download = new Date().getTime().toString() + '.xlsx';
	a.href = blobUrl;
	a.click();
}

在这里插入图片描述

在这里我需要带参数查询并下载文件

$('.export-btn').on('click', function () {
	var name = $(".searchVouchername").val();
	var voucherNo = $(".searchVoucherNo").val();
	var status = $(".searchStatus option:selected").val();
	var created_time = $(".searchCreatedTime").val();
	var arr = created_time.split('~');
	var createdstarttime = arr[0] && arr[0].trim();
	var createdendtime = arr[1] && arr[1].trim();
	var username = $(".searchUsername").val();
	var receivetime = $(".searchReceiveTime").val();
	arr = receivetime.split('~');
	var receivestarttime = arr[0] && arr[0].trim();
	var receiveendtime = arr[1] && arr[1].trim();
	
	var pinurl = '?name=' + name + '&voucherNo=' + voucherNo + '&status=' + status + '&createdstarttime=' + createdstarttime + '&createdendtime=' + createdendtime + '&username=' + username
		 + '&receivestarttime=' + receivestarttime + '&receiveendtime=' + receiveendtime
	var url = baseurl+ '/admin/voucher/export' + pinurl;
	
	handleDownLoad(url);
});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在前端使用Vue发送请求下载PDF文件需要用到两个技术:axios和Blob。 首先,在Vue项目中安装axios: ``` npm install axios --save ``` 然后,在Vue组件中使用axios发送请求下载PDF文件: ```javascript import axios from 'axios' export default { methods: { downloadPDF() { axios({ url: 'your-backend-api', method: 'GET', responseType: 'blob' // 返回类型为blob }).then(response => { const url = window.URL.createObjectURL(new Blob([response.data])) const link = document.createElement('a') link.href = url link.setAttribute('download', 'file.pdf') // 下载文件名 document.body.appendChild(link) link.click() }) } } } ``` 在代码中,我们设置了axios的请求类型为'GET',返回类型为'blob'。当请求成功时,我们将response.data转换为Blob类型,创建URL并生成一个a标签用于下载。将a标签添加到body中,模拟用户点击下载。最后,我们需要注意设置下载文件文件名。 在后端,你需要设置响应头的Content-Type为'application/pdf',推荐使用node.js的mime模块来获取正确的Content-Type: ```javascript const fs = require('fs') const path = require('path') const mime = require('mime') app.get('/download', (req, res) => { const filePath = path.join(__dirname, 'file.pdf') const fileStream = fs.createReadStream(filePath) const contentType = mime.getType(filePath) res.setHeader('Content-Type', contentType) res.setHeader('Content-Disposition', 'attachment; filename=file.pdf') fileStream.pipe(res) }) ``` 在代码中,我们使用fs模块读取文件,使用mime模块获取正确的Content-Type并设置响应头。最后,将文件通过管道pipe到响应中,完成下载
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值