js如何判断后端返回的是文件流还是json数据格式,我们可以用判断进行处理
前端
表单数据
let formData = new FormData();
formData.append('Token', getToken());
formData.append('id', 6);
axios请求以及参数
let loadingInstance = Loading.service({ fullscreen: true }); // 设置整页遮罩
axios.post(process.env.VUE_APP_REPORT_URL+'/admin/setting.Export/exportReport',formData, {
responseType: 'blob' // 告诉Axios返回的数据是一个Blob对象
}).then(response => {
if (response.status === 200) {
console.log(response.headers['content-type'])
if(response.headers['content-type'] == 'application/json; charset=utf-8'){
console.log('json')
}else if(response.headers['content-type'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
console.log('文件流')
}else{
console.log('其他')
}
}
}).catch(error => {
loadingInstance.close();//关闭整页遮罩
console.error('Error:', error);
});
后端
返回json格式
return success([],'',200);
//导出为流媒体
header('Content-Description: File Transfer');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=".basename('cusFileAll.xlsx'));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header("Expires: 0");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
$writer->writeToStdOut();
exit();