React File Viewer 是一个轻量级、高效的 TypeScript 组件,专为在 React 应用程序中预览常见文件格式而设计。支持 PDF、Excel、DOCX、CSV 和 TXT 等多种文件格式,提供简洁的 API 和响应式设计。
npm install react-file-viewer-tsbash
npm
npm install react-file-viewer-ts
yarn
yarn add react-file-viewer-ts
pnpm
pnpm add react-file-viewer-ts
`
使用方法
$3
`jsx
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 (
type={file.type}
file={file.fileSource}
style={{ height: "100%" }}
/>
);
}
export default FileViewerComponent;
`
$3
`jsx
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 (
{file && (
type={file.type}
file={file}
/>
)}
);
}
`
API 参考
$3
| 属性名 | 类型 | 必填 | 默认值 | 说明 |
|-------------|------------------------|------|--------|-------------|
| type | string | 是 | - | 文件的 MIME 类型 |
| file | File \| string | 是 | - | 文件对象或文件 URL |
| loadingComponent | React.RectNode | 否 | - | 自定义加载内容 |
| className | string | 否 | - | 自定义容器类名 |
| style | React.CSSProperties | 否 | - | 自定义容器样式 |
| onError | (error: Error) => void | 否 | - | 预览失败时的回调函数 |
$3
| 文件格式 | 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 |
高级功能
$3
`jsx
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);
}}
/>
`
$3
`jsx
function CustomLoadingIndicator() {
return (
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
backgroundColor: '#f5f5f5'
}}>
加载文件中...
常见问题解决
$3
确保导入样式文件:
`js
import "react-file-viewer-ts/styles.css";
`
$3
提供详细的错误处理:
`jsx
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
对于大文件,提供加载进度提示:
`jsx
function FilePreviewWithProgress({ file }) {
const [progress, setProgress] = useState(0);
const onLoadingProgress = (loaded, total) => {
setProgress(Math.round((loaded / total) * 100));
};
return (
type={file.type}
file={file.source}
onLoadingProgress={onLoadingProgress}
/>
{progress < 100 && 加载中: {progress}%}
);
}
`
$3
使用代理解决 CORS 问题:
`jsx
const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
type="application/pdf"
file={proxyUrl + 'https://example.com/document.pdf'}
/>
`
使用示例
$3
`jsx
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 (
{file && fileType ? (
type={fileType}
file={file}
style={{ height: '100%' }}
/>
) : (
请选择要预览的文件
)}
);
}
export default App;
`
项目开发与贡献
$3
`bash
git clone https://gitee.com/stword/react-file-view.git
cd react-file-view
`
$3
`bash
npm install
或
yarn
`
$3
`bash
npm start
`
$3
`bash
npm run build
``