在vue中下载二进制流文件:
(header和其他请求统一在axiosUtil.ts文件中处理了,文件流的比较特殊(responseType为 blob),就单独写了,不过header是可以用的)
function loadFIle() {
const headers = axiosUtil.defaults.headers
axios({
url: config.all_urls[config.api_pre_url_index] + '/api/', // 后端接口地址
method: 'POST',
responseType: 'blob', // 指定响应类型为 blob
data: condition.query, // 请求体数据
headers: headers, // 设置请求头
})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));//生成一个 Blob URL
const link = document.createElement('a'); //添加一个虚拟的a标签
link.href = url; // 文件流生成的url
link.setAttribute('download', '健康评价报告.xlsx'); // 设置下载文件的名称 文件格式
document.body.appendChild(link);
link.click(); //模拟点击a标签
document.body.removeChild(link); // 移除 a 标签
window.URL.revokeObjectURL(url); // 清理临时 URL
})
.catch(error => {
console.error('下载文件时出错:', error);
});
}
在angular中下载二进制流文件:
错误验证根据实际情况可进行逻辑修改
//根据fid获取文件,创建本地链接
async loadFIle() {
let downloadurl = `http://`//后端接口地址
let body = {}//请求体
try {
const response: any = await this.http.post(downloadurl, body,
{
headers: this.ds.headers,
responseType: 'blob',
observe: 'response'
}).toPromise();
//根据返回的响应类型 这里加了一个错误验证
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.startsWith('application/json')) {
const errormessage = await this.blobToJson(response.body)
// 如果解析失败,打印错误信息并抛出异常。
console.error(`Unexpected JSON response: ${errormessage.message || 'Unknown error'}`);
this.showMessage(2, `导出失败!${errormessage.message}`)
throw new Error(errormessage.message || 'Unknown error');
}
else if (contentType && contentType.startsWith('application/vnd')) {
const downloadUrl = URL.createObjectURL(response.body as Blob);
this.triggerDownload(downloadUrl, '文件.xlsx')
} else {
console.error('Unsupported content type:', contentType);
throw new Error('Unsupported content type');
}
} catch (error) {
console.error('Error fetching bill excel:', error);
throw error;
}
}
async blobToJson(blob: Blob) {
// 步骤1: 将Blob转换为ArrayBuffer
const arrayBuffer = await new Response(blob).arrayBuffer();
// 步骤2: 使用TextDecoder将ArrayBuffer转换为字符串
const decoder = new TextDecoder("utf-8");
const jsonString = decoder.decode(arrayBuffer);
// 步骤3: 使用JSON.parse将字符串转换为JavaScript对象
const jsonObject = JSON.parse(jsonString);
return jsonObject;
}
/**
* 触发文件下载
* @param {string} url - 文件的下载地址
* @param {string} filename - 下载时保存为的文件名(包含扩展名)
* 此方法通过创建一个隐藏的<a>标签并模拟点击事件来触发浏览器下载指定URL的文件,
* 同时允许自定义下载文件的名称。下载完成后,该标签会被移除以清理文档对象模型(DOM),
* 并通过revokeObjectURL释放创建的URL对象,防止内存泄漏。
*/
triggerDownload(url: string, filename: string) {
const link = document.createElement('a');
link.href = url;
link.download = filename; // 自定义文件名和扩展名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// 清除创建的URL以避免内存泄漏
window.URL.revokeObjectURL(url);
}