
Product
Socket MCP Adds Org Alerts, Threat Feed Review, and Package Inspection
Socket MCP now lets AI assistants review org alerts, investigate threats using the Socket threat feed, and inspect package files in addition to dependency scoring.
react-file-viewer-ts
Advanced tools
React File Viewer 是一个轻量级、高效的 TypeScript 组件,专为在 React 应用程序中预览常见文件格式而设计。支持 PDF、Excel、DOCX、CSV 和 TXT 等多种文件格式,提供简洁的 API 和响应式设计。
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>
);
}
| 属性名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
type | string | 是 | - | 文件的 MIME 类型 |
file | File | string | 是 | - | 文件对象或文件 URL |
loadingComponent | React.RectNode | 否 | - | 自定义加载内容 |
className | string | 否 | - | 自定义容器类名 |
style | React.CSSProperties | 否 | - | 自定义容器样式 |
onError | (error: Error) => void | 否 | - | 预览失败时的回调函数 |
| 文件格式 | MIME 类型 | 扩展名 |
|---|---|---|
application/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 />}
/>
确保导入样式文件:
import "react-file-viewer-ts/styles.css";
提供详细的错误处理:
<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();
}}
/>
对于大文件,提供加载进度提示:
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>
);
}
使用代理解决 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
我们欢迎任何形式的贡献:
请确保:
本项目基于 MIT 许可证 开源,欢迎免费使用和贡献代码。
FAQs
React File Viewer 是一个轻量级、高效的 TypeScript 组件,专为在 React 应用程序中预览常见文件格式而设计。支持 PDF、Excel、DOCX、CSV 和 TXT 等多种文件格式,提供简洁的 API 和响应式设计。
The npm package react-file-viewer-ts receives a total of 23 weekly downloads. As such, react-file-viewer-ts popularity was classified as not popular.
We found that react-file-viewer-ts demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Socket MCP now lets AI assistants review org alerts, investigate threats using the Socket threat feed, and inspect package files in addition to dependency scoring.

Product
Socket Firewall blocks malicious VS Code and Open VSX extensions before install, protecting developers from compromised editor marketplaces.

Research
More than 140 Mastra npm packages were compromised in a supply chain attack that used a typosquatted dependency to deliver a cross-platform infostealer during installation.