标签:文件 const string url 前端 window blob props 下载
方法1: 前端点击下载按钮后直接发送请求,后端输出文件流。
import React from 'react'; import { Button } from 'antd'; interface Props { /** 下载地址 */ url: string; text?: string; className?: string; iconClassName?: string; /** 默认get轻轻 */ method?: 'get' | 'post'; /** 只用于post请求,如果是get请求,请自行在url中组装参数 */ data?: { [key: string]: any }; } /** * 文件下载组件 */ export default function Download(props: Props) { function createInput() { if (!props.data) return ''; return Object.entries(props.data).map(([key, value]) => ( <input type="hidden" name={key} value={value ?? ''} /> )); } return ( <div style={{ display: 'inline-block' }} className={props.className ?? ''}> <form method={props.method ?? 'get'} action={props.url} target="_self"> {createInput()} <Button type="submit"> {props.text ?? '下载数据'} </Button> </form> </div> ); }
方法2: 使用ajax发送请求,体验比上面的好
function saveFile (resBlob, fileName, fileType = '.xls') { const blob = new Blob([resBlob], { type: 'application/vnd.ms-excel;charset=utf-8' }) if (window.navigator && window.navigator.msSaveOrOpenBlob) { // 兼容IE/Edge window.navigator.msSaveOrOpenBlob(blob, fileName + fileType) } else { const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.display = 'none' a.download = fileName + fileType document.body.appendChild(a) a.click() document.body.removeChild(a) window.URL.revokeObjectURL(url) // 释放URL 对象 } } (async function(){ const res = await axios.post({ url:'/api/download',data: {}, responseType: 'blob'}) saveFile(res.blob, '文件下载') })()
标签:文件,const,string,url,前端,window,blob,props,下载 来源: https://www.cnblogs.com/94pm/p/16068517.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。