🚀 Socket Launch Week Day 4:Socket MCP Adds Org Alerts, Threat Feed Review, and Package Inspection.Learn more
Sign In

react-file-viewer-ts

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-file-viewer-ts

React File Viewer 是一个轻量级、高效的 TypeScript 组件,专为在 React 应用程序中预览常见文件格式而设计。支持 PDF、Excel、DOCX、CSV 和 TXT 等多种文件格式,提供简洁的 API 和响应式设计。

latest
npmnpm
Version
0.0.30
Version published
Weekly downloads
26
-31.58%
Maintainers
1
Weekly downloads
 
Created
Source

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 组件属性

属性名类型必填默认值说明
typestring-文件的 MIME 类型
fileFile | string-文件对象或文件 URL
loadingComponentReact.RectNode-自定义加载内容
classNamestring-自定义容器类名
styleReact.CSSProperties-自定义容器样式
onError(error: Error) => void-预览失败时的回调函数

支持的文件格式

文件格式MIME 类型扩展名
PDFapplication/pdf.pdf
Excelapplication/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.xls, .xlsx
Wordapplication/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document.doc, .docx
CSVtext/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 许可证 开源,欢迎免费使用和贡献代码。

FAQs

Package last updated on 03 Jun 2025

Did you know?

Socket

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.

Install

Related posts