前端文件下载以及跳转处理

163 阅读1分钟

我正在参加「掘金·启航计划」

前言:业务中经常有打开弹窗图片、文件跳转新页面、下载文件等等。本篇主要为业务中常见的图片 pdf doc excel等文件业务中的处理方式

一、打开文件

1、在新页面打开

<a key={index} href={item.url} target="_blank">   {item.name}</a>

注意:target="_blank"为打开新页面 

2、弹框打开

> const getBase64 = (file: RcFile): Promise<string> =>
>   new Promise((resolve, reject) => {
>     const reader = new FileReader();
>     reader.readAsDataURL(file);
>     reader.onload = () => resolve(reader.result as string);
>     reader.onerror = error => reject(error);
>   });

modal框url 或者转化为base64 具体这里就不做赘述了 

word或者pdf用iframe

<Drawer title="合同预览" placement="right" onClose={onClose} visible={contract} width={1000}>        <iframe width="100%" height="100%" src={url}></iframe>      </Drawer>

<a onClick={() => handleClickDownload(record)} key="down">

下载
</a>

二、下载

1、a标签

<a href={item.url} download key="down">
   下载</a>

download为下载 如果不可以可以用方法2

2、转化为bolb下载

> export const downloadFileByUrl = async (
> 	url: string,
> 	isCurrentSite: boolean,
> 	onDownloadProgress?: (p?: string | number) => void,
> 	fileName?: string
> ) => {
> 	let _fileUrl = url
> 	const fileBlob = await axios({
> 		headers: { Authorization: 'Bearer ' + sessionStorage.getItem('token') },
> 		method: 'get',
> 		url: baseUrl + _fileUrl.split('.com')[1],
> 		responseType: 'blob'
> 	})
> 	const fileUrl = URL.createObjectURL(fileBlob.data)
> 	const tempLink = document.createElement('a')
> 	tempLink.style.display = 'none'
> 	tempLink.href = fileUrl
> 	tempLink.download =
> 		fileName || fileBlob.headers.filename || fileBlob.headers?.['content-disposition']?.match?.(/filename=(.*)/)?.[1] || '下载'
> 	document.body.append(tempLink)
> 	tempLink.click()
> 	document.body.removeChild(tempLink)
> 	URL.revokeObjectURL(fileUrl)
> }

在这里获取fileBlob是关键 需要url以及请求

附一个文件计算大小的

> // 计算文件大小
> export const calcFileSize = (fileByte: number): string => {
> 	const KB = FileSizes.K
> 	const MB = FileSizes.M
> 	const GB = FileSizes.G
> 	const TB = FileSizes.T
> 	const FIXED_TWO_POINT = 2
> 	let fileSizeMsg = ''
> 	if (fileByte < KB) {
> 		fileSizeMsg = '文件小于1K'
> 	} else if (fileByte > KB && fileByte < MB) {
> 		fileSizeMsg = (fileByte / KB).toFixed(FIXED_TWO_POINT) + 'K'
> 	} else if (fileByte === MB) {
> 		fileSizeMsg = '1M'
> 	} else if (fileByte > MB && fileByte < GB) {
> 		fileSizeMsg = (fileByte / (KB * KB)).toFixed(FIXED_TWO_POINT) + 'M'
> 	} else if (fileByte > MB && fileByte === GB) {
> 		fileSizeMsg = '1G'
> 	} else if (fileByte > GB && fileByte < TB) {
> 		fileSizeMsg = (fileByte / (KB * KB * KB)).toFixed(FIXED_TWO_POINT) + 'G'
> 	} else {
> 		fileSizeMsg = '文件超过1T'
> 	}
> 	return fileSizeMsg
> }总结: 上面只是个人业务中处理的方式 有更好的方式欢迎留言指导