React 文件流實現文件下載


同種方法-兩種方案:

第一種:頁面上自己手動添加a標簽
第二種:js自動生成a標簽(推薦第二種)

今天在react項目開發過程中,有這樣的一個需求就是文件下載。
自己認為:通過接口請求后端發給返給自己的會是一個文件下載的地址或者路徑什么的,只要把這個地址賦值給a鏈接即可
實際情況:后端發給我的是一端文件流,那么就是需要們自動去解析文件流,然后把解析出來的數據,通過a標簽進行下載

第一種方案:
//點擊文件下載 <div style={styles.downFileBtn} onClick={(event) => { event.preventDefault(); event.stopPropagation(); fetch(downloadFiles, { //downloadFiles 接口請求地址 method: 'get', credentials: 'include', headers: new Headers({ 'Content-Type': 'application/json', 'X-Auth-Token': User.getToken(),//設置header 獲取token }) }).then((response) => { response.blob().then(blob => { let blobUrl = window.URL.createObjectURL(blob); let aElement = document.getElementById('downloadDiv'); //獲取a標簽元素 let filename = times.formatNowDate() + '.zip';//設置文件名稱 aElement.href = blobUrl;//設置a標簽路徑 aElement.download = filename; aElement.click(); window.URL.revokeObjectURL(blobUrl); }); }).catch((error) => { console.log('文件下載失敗', error); }); }} > <Icon type="download"/>文件下載 </div> //定義個a標簽數組 const Anchor = props => { return ( <a {...props}>{props.children}</a> ); }; //頁面上使用a標簽數組 <Anchor id="downloadDiv" style={{display: 'none'}}></Anchor> //隱藏不顯示 
第二種方案:(這塊我封裝了一個組件)
/** * @desc:這是一個文件下載組件 * @param:參數說明 * api_url:接口地址 * icon: 下載圖片設置 * text: 下載文本設置 * downFileBtnClass: 按鈕樣式設置 */ import React, {PureComponent} from 'react'; import PropTypes from 'prop-types'; import {Button, Icon} from 'antd'; import User from '/utils/user'; import times from '_TOOLS_/times'; import styles from './index.less'; const downFileBtn = styles.downFileBtn; class FileDown extends PureComponent { constructor(props) { super(props); this.state = { loadingStatus: true, buttonDisabled: false } } //文件下載操作 handleDownFile = (event, api_url) => { event.preventDefault(); event.stopPropagation(); //開啟loading 按鈕置灰 this.setState({ loadingStatus: false, buttonDisabled: true, }); fetch(api_url, { method: 'get', credentials: 'include', headers: new Headers({ 'Content-Type': 'application/json', 'X-Auth-Token': User.getToken(), }), }).then((response) => { response.blob().then(blob => { //關閉loading 按鈕恢復正常 this.setState({ loadingStatus: true, buttonDisabled: false, }); let blobUrl = window.URL.createObjectURL(blob); const filename = times.formatNowDate() + '.zip'; const aElement = document.createElement('a'); document.body.appendChild(aElement); aElement.style.display = 'none'; aElement.href = blobUrl; aElement.download = filename; aElement.click(); document.body.removeChild(aElement); }); }).catch((error) => { //關閉loading 按鈕恢復正常 this.setState({ loadingStatus: false, buttonDisabled: false, }); console.log('文件下載失敗', error); }); }; render() { const {api_url, text, icon, downFileBtnClass} = this.props; const {loadingStatus, buttonDisabled} = this.state; return ( <Button type="primary" className={downFileBtnClass} onClick={(event) => this.handleDownFile(event, api_url)} disabled={buttonDisabled} > <Icon type={loadingStatus ? icon : 'loading'}/> {loadingStatus ? text : '下載中...'} </Button> ); } } //定義屬性 類型以及是否必填項 FileDown.proTypes = { api_url: PropTypes.isRequired }; //定義屬性的默認值 FileDown.defaultProps = { text: '文件下載', icon: 'download', downFileBtnClass: downFileBtn, }; export default FileDown; 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM