🎯 目标
封装一个通用文件预览组件 FilePreview
,适用于:
- 文件上传后的预览(图片 / PDF / 音频 / 文本)
- 支持文件名、大小、下载按钮、文件类型图标
- 图片支持缩略图点击放大
- PDF / 音频使用系统能力或第三方框架预览
- 适配桌面与移动端预览需求,后续支持权限控制与分布式打开
🧱 展示结构示意
🖼 图片.jpg [预览] [下载]
📄 文档.pdf [打开]
🎵 音频.mp3 [播放]
🧰 组件实现:FilePreview.ets
@Component
export struct FilePreview {
@Prop files: Array<{
name: string
url: string
type: 'image' | 'pdf' | 'audio' | 'text' | 'other'
}> = []
@Prop onDownload: (file: { name: string; url: string }) => void = () => {}
@Prop onOpen: (file: { name: string; url: string }) => void = () => {}
build() {
Column({ space: 16 }) {
this.files.forEach(file => {
Row()
.padding(12)
.backgroundColor('#f8f8f8')
.borderRadius(8)
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.SpaceBetween) {
Row({ space: 8 }).alignItems(VerticalAlign.Center) {
Text(this.getIcon(file.type)).fontSize(18)
Text(file.name).fontSize(14).fontColor('#333').maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis })
}
Row({ space: 12 }) {
if (file.type === 'image') {
Button('预览').type(ButtonType.Normal).fontSize(12).onClick(() => this.previewImage(file.url))
} else if (file.type === 'pdf' || file.type === 'audio' || file.type === 'text') {
Button('打开').type(ButtonType.Normal).fontSize(12).onClick(() => this.onOpen(file))
}
Button('下载').type(ButtonType.Normal).fontSize(12).onClick(() => this.onDownload(file))
}
}
})
}
}
private getIcon(type: string): string {
return {
image: '🖼',
pdf: '📄',
audio: '🎵',
text: '📝'
}[type] ?? '📁'
}
private previewImage(url: string) {
router.pushUrl(`/preview/image?src=${encodeURIComponent(url)}`)
}
}
📦 使用示例
@Entry
@Component
struct DemoFilePreview {
build() {
FilePreview({
files: [
{ name: '头像.jpg', url: 'https://example.com/avatar.jpg', type: 'image' },
{ name: '课程资料.pdf', url: 'https://example.com/doc.pdf', type: 'pdf' },
{ name: '背景音乐.mp3', url: 'https://example.com/music.mp3', type: 'audio' }
],
onDownload: file => {
console.info(`下载文件:${file.name}`)
},
onOpen: file => {
console.info(`打开文件:${file.name}`)
}
})
}
}
✨ 可扩展能力建议
功能 | 说明 |
---|---|
文件类型自动识别 | 根据文件名后缀自动判断类型 |
预览大图全屏 + 滑动 | 图片支持点击放大 + 多图滑动预览 |
文件权限控制(禁看/限下载) | 针对不同用户角色控制是否展示“下载/预览”按钮 |
分布式设备打开文件支持 | 接入 startRemoteAbility 将文件投送到指定设备查看 |
📘 下一篇预告
第46篇:【HarmonyOS 5.0.0 或以上】构建语音输入组件 VoiceInput:集成语音识别 / 实时转文字 / 语音指令响应