前言
最近有接到一个需求,要求前端支持上传制定后缀文件,且支持页面预览,上传简单,那么预览该怎么实现呢,尤其是不同类型的文件预览方案,那么下面就我这个需求的实现,分不同情况来讲解一下👇
具体的预览需求: 预览需要支持的文件类型有: png、jpg、jpeg、docx、xlsx、ppt、pdf、md、txt、audio、video,另外对于不同文档还需要有定位的功能。例如:pdf 定位到页码,txt和markdown定位到文字并滚动到指定的位置,音视频定位到具体的时间等等。
⚠️ 补充: 我的需求是需要先将文件上传到后台,然后我拿到url地址去展示,对于markdown和txt的文件需要先用fetch获取,其他的展示则直接使用url链接就可以。
不同文件的实现方式不同,下面分类讲解,总共分为以下几类:
-
自有标签文件:
png、jpg、jpeg、audio、video -
纯文字的文件:
markdown & txt -
office类型的文件:docx、xlsx、ppt -
embed引入文件:pdf -
iframe:引入外部完整的网站
自有标签文件:png、jpg、jpeg、audio、video
对于图片、音视频的预览,直接使用对应的标签即可,如下:
图片:png、jpg、jpeg
示例代码:
<img src={url} key={docId} alt={name} width="100%" />;
预览效果如下:

音频:audio
示例代码:
<audio ref={audioRef} controls controlsList="nodownload" style={
{ width: '100%' }}>
<track kind="captions" />
<source src={url} type="audio/mpeg" />
</audio>
预览效果如下:

视频:video
示例代码:
<video ref={videoRef} controls muted controlsList="nodownload" style={
{ width: '100%' }}>
<track kind="captions" />
<source src={url} type="video/mp4" />
</video>
预览效果如下:

关于音视频的定位的完整代码:
import React, { useRef, useEffect } from 'react'
interface IProps {
type: 'audio' | 'video'
url: string
timeInSeconds: number
}
function AudioAndVideo(props: IProps) {
const { type, url, timeInSeconds } = props
const videoRef = useRef<HTMLVideoElement>(null)
const audioRef = useRef<HTMLAudioElement>(null)
useEffect(() => {
// 音视频定位
const secondsTime = timeInSeconds / 1000
if (type === 'audio' && audioRef.current) {
audioRef.current.currentTime = secondsTime
}
if (type === 'video' && videoRef.current) {
videoRef.current.currentTime = secondsTime
}
}, [type, timeInSeconds])
return (
<div>
{type === 'audio' ? (
<audio ref={audioRef} controls controlsList="nodownload" style={
{ width: '100%' }}>
<track kind="captions" />
<source src={url} type="audio/mpeg" />
</audio>
) : (
<video ref={videoRef} controls muted controlsList="nodownload" style={
{ width: '100%' }}>
<track kind="captions" />
<source src={url} type="video/mp4" />
</video>
)}
</div>
)
}
export default AudioAndVideo

最低0.47元/天 解锁文章
2275

被折叠的 条评论
为什么被折叠?



