import { message, Progress } from 'antd'; import { AxiosResponse } from 'axios'; import React from 'react'; import { useContext, useEffect, useState } from 'react' import { DownloadFile, DownloadState } from './download-panel'; import './download-panel.less' interface IProps { file: DownloadFile, stopSignal: boolean, onComplete: () => void, downloadContext: React.Context, getFileUrl: (params?: {}) => Promise> } export default function DownloadItem(props: IProps) { const downloadContext = useContext(props.downloadContext); const [progress, setProgress] = useState(0); const [msg, setMsg] = useState(''); const xhr = new XMLHttpRequest(); useEffect(() => { if (downloadContext.visible) { xhr.abort(); start(); } }, [downloadContext.visible]) xhr.onload = () => { if (xhr.status === 200) { setMsg('下载完毕!'); // resolve(xhr.response) downloadFile(xhr.response); } } xhr.onprogress = (e) => { let p = Math.round(e.loaded / e.total * 100); setProgress(p); } xhr.onerror = (e) => { console.log(e) setMsg('发生错误,下载失败'); props.onComplete(); } const getBlob = (url) => { // const xhr = new XMLHttpRequest(); xhr.open('GET', url, true) xhr.responseType = 'blob' xhr.send() } const start = () => { let file = props.file; if (file == null) { setMsg('文件信息异常,下载被取消'); props.onComplete(); return; } if (file.url) { setMsg(`开始下载:${file.filename}${file.suffix || ''}`) getBlob(file.url); return; }else{ if(file.bucketName && file.filename && file.objectName && file.suffix && props.getFileUrl){ setMsg('正在获取下载链接...'); props.getFileUrl(file).then(res => { let url = res.data; if (url == null) { setMsg('文件不存在或已被清理,下载终止'); props.onComplete(); return; } setMsg(`开始下载:${file.filename}${file.suffix || ''}`) getBlob(url); }).catch(err => { console.error(err); setMsg('文件不存在或已被清理,下载终止'); props.onComplete(); }) }else{ message.warning("文件信息不全或api不存在!") } } } const downloadFile = (blob: any) => { let file = props.file; let link = document.createElement("a"); link.style.display = 'none' let href = window.URL.createObjectURL(blob); let downloadName = `${file.filename}${file.suffix || ''}`; link.setAttribute('href', href); // link.setAttribute('download', downloadName); link.download = downloadName document.body.appendChild(link); link.click(); document.body.removeChild(link); props.onComplete(); } useEffect(() => { if (!!props.stopSignal) { xhr.abort(); setProgress(0); setMsg(''); } }, [props.stopSignal]) return (
{msg}
) }