react-file-viewer-ts
v0.0.30
Published
React File Viewer 是一个轻量级、高效的 TypeScript 组件,专为在 React 应用程序中预览常见文件格式而设计。支持 PDF、Excel、DOCX、CSV 和 TXT 等多种文件格式,提供简洁的 API 和响应式设计。
Downloads
18
Readme
React File Viewer (TypeScript) - 文件预览组件
概述
React File Viewer 是一个轻量级、高效的 TypeScript 组件,专为在 React 应用程序中预览常见文件格式而设计。支持 PDF、Excel、DOCX、CSV 和 TXT 等多种文件格式,提供简洁的 API 和响应式设计。
安装
# npm
npm install react-file-viewer-ts
# yarn
yarn add react-file-viewer-ts
# pnpm
pnpm add react-file-viewer-ts使用方法
基础用法
import React from 'react';
import { FilePreview } from "react-file-viewer-ts";
import "react-file-viewer-ts/styles.css";
function FileViewerComponent() {
// 示例文件
const file = {
type: 'application/pdf',
// 使用本地文件或URL
fileSource: new File([], 'document.pdf') || 'https://example.com/document.pdf'
};
return (
<div style={{ height: '100vh' }}>
<FilePreview
type={file.type}
file={file.fileSource}
style={{ height: "100%" }}
/>
</div>
);
}
export default FileViewerComponent;结合文件上传功能
import React, { useState } from 'react';
import { FilePreview } from "react-file-viewer-ts";
import "react-file-viewer-ts/styles.css";
function FileUploader() {
const [file, setFile] = useState(null);
const handleFileChange = (e) => {
const selectedFile = e.target.files[0];
if (selectedFile) {
setFile(selectedFile);
}
};
return (
<div>
<input type="file" onChange={handleFileChange} accept=".pdf,.docx,.xlsx,.csv,.txt" />
{file && (
<div className="preview-container" style={{ marginTop: '20px', height: '80vh' }}>
<FilePreview
type={file.type}
file={file}
/>
</div>
)}
</div>
);
}API 参考
FilePreview 组件属性
| 属性名 | 类型 | 必填 | 默认值 | 说明 |
|-------------|------------------------|------|--------|-------------|
| type | string | 是 | - | 文件的 MIME 类型 |
| file | File | string | 是 | - | 文件对象或文件 URL |
| loadingComponent | React.RectNode | 否 | - | 自定义加载内容 |
| className | string | 否 | - | 自定义容器类名 |
| style | React.CSSProperties | 否 | - | 自定义容器样式 |
| onError | (error: Error) => void | 否 | - | 预览失败时的回调函数 |
支持的文件格式
| 文件格式 | MIME 类型 | 扩展名 |
|------------|---------------------------------------------------------------------------|-----------------|
| PDF | application/pdf | .pdf |
| Excel | application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | .xls, .xlsx |
| Word | application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document | .doc, .docx |
| CSV | text/csv | .csv |
| 纯文本 | text/plain | .txt |
高级功能
自定义错误处理
<FilePreview
type="application/pdf"
file="https://example.com/missing.pdf"
onError={(error) => {
// 自定义错误处理逻辑
console.error('文件预览失败:', error.message);
alert('无法加载PDF文件,正在提供下载链接...');
// 提供下载链接
const downloadLink = document.createElement('a');
downloadLink.href = 'https://example.com/missing.pdf';
downloadLink.download = 'document.pdf';
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}}
/>自定义加载状态
function CustomLoadingIndicator() {
return (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
backgroundColor: '#f5f5f5'
}}>
<div className="spinner"></div>
<span style={{ marginLeft: '10px' }}>加载文件中...</span>
</div>
);
}
// 在预览组件中使用
<FilePreview
type="application/pdf"
file={pdfFile}
loadingComponent={<CustomLoadingIndicator />}
/>常见问题解决
1. 样式不生效
确保导入样式文件:
import "react-file-viewer-ts/styles.css";2. 文件预览失败
提供详细的错误处理:
<FilePreview
type={file.type}
file={file.source}
onError={(error) => {
// 显示错误提示
alert(`文件预览失败: ${error.message}`);
// 提供替代方案
const downloadLink = document.createElement('a');
downloadLink.href = file.source;
downloadLink.download = file.name;
downloadLink.click();
}}
/>3. 大文件加载缓慢
对于大文件,提供加载进度提示:
function FilePreviewWithProgress({ file }) {
const [progress, setProgress] = useState(0);
const onLoadingProgress = (loaded, total) => {
setProgress(Math.round((loaded / total) * 100));
};
return (
<div>
<FilePreview
type={file.type}
file={file.source}
onLoadingProgress={onLoadingProgress}
/>
{progress < 100 && <div>加载中: {progress}%</div>}
</div>
);
}4. 跨域问题
使用代理解决 CORS 问题:
const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
<FilePreview
type="application/pdf"
file={proxyUrl + 'https://example.com/document.pdf'}
/>使用示例
完整的文件预览页面
import React, { useState } from 'react';
import { FilePreview } from "react-file-viewer-ts";
import "react-file-viewer-ts/styles.css";
function App() {
const [file, setFile] = useState(null);
const [fileType, setFileType] = useState('');
// 从API获取文件信息
const fetchFileInfo = async (fileId) => {
try {
const response = await fetch(`/api/files/${fileId}`);
const data = await response.json();
setFile(data.fileUrl); // 或 data.fileContent
setFileType(data.mimeType);
} catch (error) {
console.error('获取文件信息失败:', error);
}
};
useEffect(() => {
fetchFileInfo('12345'); // 从路由参数或其他来源获取文件ID
}, []);
return (
<div className="file-preview-page" style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
{file && fileType ? (
<div className="preview-container" style={{ flex: 1 }}>
<FilePreview
type={fileType}
file={file}
style={{ height: '100%' }}
/>
</div>
) : (
<div className="empty-state" style={{ textAlign: 'center', padding: '2rem' }}>
<p>请选择要预览的文件</p>
</div>
)}
</div>
);
}
export default App;项目开发与贡献
克隆仓库
git clone https://gitee.com/stword/react-file-view.git
cd react-file-view安装依赖
npm install
# 或
yarn开发模式
npm start生产构建
npm run build贡献指南
我们欢迎任何形式的贡献:
- 提交 bug 报告或功能请求
- 创建 pull 请求
- 完善文档
请确保:
- 代码符合 TypeScript 规范
- 添加必要的测试
- 更新相关文档
许可证
本项目基于 MIT 许可证 开源,欢迎免费使用和贡献代码。
