React中实现文件预览

2,934 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

1.使用iframe

用iframe标签src="文件地址"就能够直接打开

2.使用react-file-viewer

npm install react-file-viewerw

在组件中引入

import FileViewer from 'react-file-viewer';

let path;
// path:文件地址,如果是本地文件,放入public文件夹中,path='a/docx'

<FileViewer 
   fileType='docx'//文件类型
   filePath={path} //文件地址
   onError={this.onError.bind(this)} //函数[可选]:当文件查看器在获取或呈现请求的资源时发生错误时将调用的函数。在这里能够传递日志记录实用程序的回调。
   errorComponent={console.log("出现错误")} //[可选]:发生错误时呈现的组件,而不是react-file-viewer随附的默认错误组件。
   unsupportedComponent={console.log("不支持")} //[可选]:在不支持文件格式的状况下呈现的组件。
  />