網站首頁 編程語言 正文
使用react-file-viewer
1.npm install react-file-viewer
2.在組建中引入import FileViewer from 'react-file-viewer';
3.使用:
<FileViewer
fileType={this.state.imgFlieType}//文件類型
filePath={this.state.details.dragger}//文件地址
onError={console.log('錯誤信息')}
errorComponent={console.log('發生錯誤')}//[可選]:發生錯誤時呈現的組件,而不是react-file-
viewer隨附的默認錯誤組件
unsupportedComponent={console.log('不支持')} //[可選]:在不支持文件格式的情況下呈現的組件
/>
注意:
在使用插件時出現如下報錯時:
原因:react-file-viewer只支持文件網絡地址,本地地址可能不支持
解決辦法:需要把本地地址換成網絡地址進行測試
react-file-viewer預覽本地文件
代碼
import React, {Component} from 'react';
import FileViewer from 'react-file-viewer';
export default class MyComponent extends Component {
state = {
fileLocalUrl: null,
type: ''
}
changeFile(e) {
let file = e.currentTarget.files[0]
let fileName = file.name
console.log(file)
window.URL = window.URL || window.webkitURL;
this.setState({
fileLocalUrl: window.URL.createObjectURL(file),
type: fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)
})
}
render() {
const {fileLocalUrl, type} = this.state
return (
<div>
{
fileLocalUrl && <FileViewer
fileType={type}
filePath={fileLocalUrl}
errorComponent={<div>錯誤</div>}
onError={this.onError}/>
}
<input type="file" onChange={e => this.changeFile(e)}/>
</div>
);
}
}
能遇到這個問題的大部分都是直接把file丟進組件,導致報錯
解決思路
window.URL.createObjectURL,創建文件對象的URL,將URL丟進組件即可
在移除文件對象URL的時候記得調用URL.revokeObjectURL(url),清理內存,否則會一直存在內存中,詳見官網
https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
對于大文件可能會導致內存崩潰,切記不要預覽大文件,最好限制在30M以內
原文鏈接:https://blog.csdn.net/qq_52886072/article/details/122622404
相關推薦
- 2022-07-09 C++超詳細講解auto與nullptr的使用_C 語言
- 2023-01-02 C語言刪除輸入字符串中的空格示例代碼_C 語言
- 2022-12-09 python返回多個值與賦值多個值的示例代碼_python
- 2023-04-01 Android自定義View?Material?Design理念詳解_Android
- 2022-11-22 Golang?Compare?And?Swap算法詳細介紹_Golang
- 2022-07-03 el-upload上傳組件的動態添加;el-upload動態上傳文件;el-upload區分文件是哪
- 2022-08-15 Python包裝之對象處理_python
- 2023-02-09 Python的Flask項目中獲取請求用戶IP地址?addr問題_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支