最近做一個項目要求在前端瀏覽器可以直接打開office文件(pdf,doc,xlsx等文件)。pdf瀏覽器可以直接打開(可以直接用a標簽href="文件地址"或者iframe標簽src="文件地址"再或者使用pdf.js)。但是word,xlsl等文件很難實現,網上的實現方式有微軟的方法實現但是訪問的文件地址必須是公共文件,所有人都能訪問到才可以使用,顯然是不行的,所以我就找到了react-file-viewer。
1.實現pdf預覽。
(1)用iframe標簽src="文件地址"就可以直接打開,還可以設置width,height等屬性。具體參考iframe屬性。
<iframe src="http://localhost:8080/%E9%9F%A6%E6%88%90%E7%8E%89.pdf"></iframe>
(2)直接a標簽src="文件地址"
<a href="文件地址"></a>
2.使用react-file-viewer實現(pdf,word,xlsx文件)預覽
1.npm install react-file-viewer
2.在組建中引入import FileViewer from 'react-file-viewer';
3.直接使用(涉及到跨域問題自行解決可以使用代理來解決別的方案也可行)
<FileViewer
fileType='docx'//文件類型
filePath={wo} //文件地址(后台給返的二進制流也可以)
onError={this.onError.bind(this)} //函數[可選]:當文件查看器在獲取或呈現請求的資源時發生錯誤時將調用的函數。在這里可以傳遞日志記錄實用程序的回調。
errorComponent={console.log("出現錯誤")} //[可選]:發生錯誤時呈現的組件,而不是react-file-viewer隨附的默認錯誤組件。
unsupportedComponent={console.log("不支持")} //[可選]:在不支持文件格式的情況下呈現的組件。
/>
支持的文件格式:
圖片:png,jpeg,gif,bmp,包括360度圖片
pdf格式
CSV
xslx
docx
視頻:mp4,webm
音頻:mp3
用法
請注意,此模塊最適合React 16+。如果您使用React <16,則可能需要使用版本0.5。npm install react-file-viewer@0.5.0。
有一個主要的React組件FileViewer,它具有以下道具:
fileType字符串:要顯示的資源類型(一種受支持的文件格式,例如'png')。傳遞不支持的文件類型將導致顯示unsupported file type消息(或自定義組件)。
filePath 字符串:FileViewer顯示的資源的URL(后台給返的二進制流也可以)。
onError函數[可選]:當文件查看器在獲取或呈現請求的資源時發生錯誤時將調用的函數。在這里可以傳遞日志記錄實用程序的回調。
errorComponent react元素[可選]:發生錯誤時呈現的組件,而不是react-file-viewer隨附的默認錯誤組件。
unsupportedComponent react元素[可選]:在不支持文件格式的情況下呈現的組件。
3. react-file-viewer報錯(采坑只限瀏覽本地文件)
這個是因為后端還沒做好,我拿本地文件做測試才會遇到.我把本地docx文件放到了assets文件中然后引入遇到一堆問題。
<FileViewer fileType='docx'
filePath='../../../assets/ss.docx'
onError={this.onError.bind(this)}
errorComponent={console.log("出現錯誤")}
unsupportedComponent={console.log("不支持")}
/>
(1)瀏覽器報:Module parse failed: Unexpected character '' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file
cmd運行窗口報:Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file
造成這兩個錯誤的根本原因是react不識別后綴名為.docx的文件。
解決方案:
去webpack(webpack.config.js)里面配置文件后綴名在module.exports加入
{
test: /\.(pdf|svg|docx|doc)$/,
use: 'file-loader',//如果不可以試試這個file-loader?name=[path][name].[ext]
}
本以為這樣就好了,現實是還是不行頁面還是不顯示一直轉圈並且瀏覽器報找不到http://localhost:8888/assets/ss.docx,但是我地址寫對了,找了很久都不知到原因最后換了種方式就可以了。
解決方案:用require或者import來引入就行了(react項目中圖片出不來用require也可以解決);
<FileViewer fileType='docx'
filePath={require('../../../assets/ss.docx')}
onError={this.onError.bind(this)}
errorComponent={console.log("出現錯誤")}
unsupportedComponent={console.log("不支持")}
/>
//或者直接用在上面定義變量引入
const wo=require("../../../assets/ss.docx");//這個也可以
import wo from '../../../assets/ss.docx'; //require,import只保留一個
<FileViewer fileType='docx'
filePath={wo}
onError={this.onError.bind(this)}
errorComponent={console.log("出現錯誤")}
unsupportedComponent={console.log("不支持")}
/>