Javascript 无法在React js中加载PDF文件
我正在开发一个简单的react web应用程序,它可以在IPFS中添加和检索文件 将文件添加到IPFS时,页面上将显示添加文件(即医疗文件)的名称以及“查看文件”按钮 单击按钮时,应使用react pdf[react pdf|中的“文档”组件查看文件 (Document file=“…”。该文件可以是URL、base64内容、Uint8Array等。) 从IPFS添加和检索文件成功。从IPFS检索到的文件以Uint8Array的形式传递到Main.js组件中的文档组件以查看pdf文件。但是,页面未能加载pdf文件。此外,我还收到一个错误:Javascript 无法在React js中加载PDF文件,javascript,reactjs,this,ipfs,react-pdf,Javascript,Reactjs,This,Ipfs,React Pdf,我正在开发一个简单的react web应用程序,它可以在IPFS中添加和检索文件 将文件添加到IPFS时,页面上将显示添加文件(即医疗文件)的名称以及“查看文件”按钮 单击按钮时,应使用react pdf[react pdf|中的“文档”组件查看文件 (Document file=“…”。该文件可以是URL、base64内容、Uint8Array等。) 从IPFS添加和检索文件成功。从IPFS检索到的文件以Uint8Array的形式传递到Main.js组件中的文档组件以查看pdf文件。但是,页面
Error: "Setting up fake worker failed: "window.pdfjsWorker is undefined"."
请注意,Main.js中包含以下内容:
<Document file={{ data: pdfFile.content }}></Document>
App.js
import React, { Component } from "react";
import Web3 from "web3";
import "./App.css";
import Meme from "../abis/Meme";
import Addressbar from "./Addressbar";
import Main from "./Main";
class App extends Component {
async componentDidMount() {
await this.getWeb3Provider();
this.loadBlockchainData();
}
async getWeb3Provider() {
if (window.ethereum) {
window.web3 = new Web3(window.ethereum);
await window.ethereum.enable();
} else if (window.web3) {
window.web3 = new Web3(window.web3.currentProvider);
} else {
window.alert(
"Non-Ethereum browser detected. You should consider trying MetaMask!"
);
}
}
async loadBlockchainData() {
const web3 = window.web3;
// Load the account
const accounts = await web3.eth.getAccounts();
this.setState({ account: accounts[0] });
/*Get an instance of the deployed smart contract in Javascript to allow us to
call the functions of the smart contract*/
const networkId = await web3.eth.net.getId();
const networkData = Meme.networks[networkId];
if (networkData) {
const contract = new web3.eth.Contract(Meme.abi, networkData.address);
this.setState({ contract: contract });
// Fetching the file hashes from the smart contract
const count = await contract.methods.getfileHashesCount().call();
for (var i = 0; i < count; i++) {
const fileHash = await contract.methods.fileHashes(i).call();
this.setState({
fileHashes: [...this.state.fileHashes, fileHash]
});
}
} else {
window.alert("The contract is not found in your blockchain.");
}
}
constructor(props) {
super(props);
// Setting the account (1)
this.state = {
account: null,
fileHashes: [],
contract: null,
buffer: null
};
}
// Setting the buffer
setBuffer = data => {
this.setState({ buffer: data });
console.log("buffer data", this.state.buffer);
};
// Storing/adding the file hash on the blockchain
storeFileHash = hash => {
this.state.contract.methods
.addFileHash(hash)
.send({ from: this.state.account })
.then(r => {
return this.setState({ fileHashes: [...this.state.fileHashes, hash] });
});
//console.log("fileHashes", this.state.fileHashes);
};
render() {
return (
<div className="container">
<div>
<Addressbar account={this.state.account} />
</div>
<div>
<Main
fileHashes={this.state.fileHashes}
setBuffer={this.setBuffer}
buffer={this.state.buffer}
storeFileHash={this.storeFileHash}
/>
</div>
</div>
);
}
}
export default App;
import React,{Component}来自“React”;
从“Web3”导入Web3;
导入“/App.css”;
从“./abis/Meme”导入Meme;
从“/Addressbar”导入地址栏;
从“/Main”导入Main;
类应用程序扩展组件{
异步组件didmount(){
等待此消息。getWeb3Provider();
这是loadBlockchainData();
}
异步getWeb3Provider(){
if(window.ethereum){
window.web3=新的web3(window.ethereum);
wait window.ethereum.enable();
}else if(window.web3){
window.web3=新的web3(window.web3.currentProvider);
}否则{
窗口警报(
“检测到非EnthUM浏览器。您应该考虑尝试元代码!”
);
}
}
异步loadBlockchainData(){
const web3=window.web3;
//加载帐户
const accounts=wait web3.eth.getAccounts();
this.setState({account:accounts[0]});
/*获取Javascript中已部署智能合约的实例,以便
调用智能合约的功能*/
const networkId=wait web3.eth.net.getId();
const networkData=Meme.networks[networkId];
if(网络数据){
const contract=new web3.eth.contract(Meme.abi,networkData.address);
this.setState({contract:contract});
//从智能合约获取文件哈希
const count=await contract.methods.getfileHashesCount().call();
对于(变量i=0;i{
this.setState({buffer:data});
log(“缓冲区数据”,this.state.buffer);
};
//在区块链上存储/添加文件哈希
storeFileHash=hash=>{
这个。状态。合同。方法
.addFileHash(哈希)
.send({from:this.state.account})
.然后(r=>{
返回此.setState({fileHashes:[…this.state.fileHashes,hash]});
});
//log(“fileHashes”,this.state.fileHashes);
};
render(){
返回(
);
}
}
导出默认应用程序;
Main.Js
import React, { Component } from "react";
import { Document, Page } from "react-pdf";
//import { Document } from "react-pdf/dist/entry.webpack";
//import { pdfjs } from "react-pdf";
//pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
//Required module(s)
const ipfsAPI = require("ipfs-api");
/*** Connceting to the ipfs network via infura gateway ***/
const ipfs = ipfsAPI("ipfs.infura.io", "5001", { protocol: "https" });
export class Main extends Component {
/*
state = {
pdfFiles: []
};
*/
state = {
pdfFiles: [],
text: "Hi World"
};
captureFile = event => {
event.preventDefault();
// Fetch the file chosen
const file = event.target.files[0];
console.log("The original file : ", file);
// Convert the file to a buffer
const reader = new window.FileReader();
reader.readAsArrayBuffer(file);
reader.onloadend = () => {
const arr = new Uint8Array(reader.result);
console.log("Uint8Array ouptut", arr);
console.log("reader.result output : ", reader.result);
console.log("Buffer(reader.result) output : ", Buffer(reader.result));
this.props.setBuffer(Buffer(reader.result));
};
};
onSubmit = event => {
event.preventDefault();
console.log("Submitting file to IPFS......");
console.log(this.props.buffer);
// Adding the file to IPFS
ipfs.files.add(this.props.buffer, (error, result) => {
if (error) {
console.log(error);
return;
}
console.log("File added succesfully");
console.log("IPFS result", result);
// Storing the file hash on the blockchain
this.props.storeFileHash(result[0].hash);
});
}; // end of sumbit event
onClick = event => {
event.preventDefault();
console.log("Button clicked......");
console.log(this.state.text);
/*** Getting the uploaded file via hash code ***/
const that = this; // NECESSARY
ipfs.files.cat(event.target.name, function(err, file) {
console.log("Getting files from IPFS ....... ");
//console.log("File path ", file.path);
//console.log("File hash", file.hash);
console.log("The Unit8Array file content: ", file);
const unit8Array_ = {
content: file
};
console.log("Printing (1)......", unit8Array_.content);
that.setState({ text: "Hi America" });
console.log(that.state.text);
that.setState({ pdfFiles: [...that.state.pdfFiles, unit8Array_] });
});
}; // end of sumbit event
render() {
return (
<div className="container-fluid mt-5">
<div className="row">
<main>
<div>
<h3>Medical Files-Upload: </h3>
<form onSubmit={this.onSubmit}>
<div>
<label className="mr-2">Upload your medical document:</label>
<input type="file" onChange={this.captureFile} />
<input type="submit" />
</div>
</form>
</div>
<hr></hr>
<div>
<h5>PDF Document: {this.state.text} </h5>
{this.state.pdfFiles.map((pdfFile, key) => {
return (
<div>
<p>{console.log("Printing (2)....", pdfFile.content)}</p>
<Document file={{ data: pdfFile.content }}></Document>
</div>
);
})}
</div>
<hr></hr>
<div>
<h3>Medical Files-View: </h3>
{this.props.fileHashes.map((fileHash, key) => {
return (
<p>
{" "}
Medical File{" "}
<button name={fileHash} onClick={this.onClick}>
View File
</button>{" "}
</p>
);
})}
</div>
</main>
</div>
</div>
);
}
}
export default Main;
import React,{Component}来自“React”;
从“react pdf”导入{Document,Page};
//从“react pdf/dist/entry.webpack”导入{Document};
//从“react pdf”导入{pdfjs};
//pdfjs.GlobalWorkerOptions.workerSrc=`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
//所需模块
常量ipfsAPI=要求(“ipfs api”);
/***通过infura网关连接到ipfs网络***/
const ipfs=ipfsAPI(“ipfs.infura.io”,“5001”,{protocol:“https”});
导出类主扩展组件{
/*
状态={
PDF文件:[]
};
*/
状态={
Pdfiles:[],
文字:“嗨,世界”
};
captureFile=事件=>{
event.preventDefault();
//获取所选的文件
const file=event.target.files[0];
log(“原始文件:”,文件);
//将文件转换为缓冲区
const reader=new window.FileReader();
reader.readAsArrayBuffer(文件);
reader.onloadend=()=>{
const arr=新的Uint8Array(reader.result);
console.log(“Uint8Array-ouptut”,arr);
log(“reader.result输出:”,reader.result);
log(“Buffer(reader.result)输出:”,Buffer(reader.result));
this.props.setBuffer(缓冲区(reader.result));
};
};
onSubmit=事件=>{
event.preventDefault();
console.log(“向IPFS提交文件……”);
log(this.props.buffer);
//将文件添加到IPFS
添加(this.props.buffer,(错误,结果)=>{
如果(错误){
console.log(错误);
返回;
}
log(“成功添加文件”);
日志(“IPFS结果”,结果);
//将文件散列存储在区块链上
this.props.storeFileHash(结果[0].hash);
});
};//sumbit事件的结束
onClick=event=>{
event.preventDefault();
console.log(“点击按钮……”);
log(this.state.text);
/***通过哈希代码获取上传的文件***/
const that=this;//必要
ipfs.files.cat(event.target.name,函数(err,file){
log(“从IPFS获取文件……”);
//log(“文件路径”,File.path);
//log(“文件散列”,File.hash);
log(“Unit8Array文件内容:”,文件);
常量单位8数组={
内容:文件
};
console.log(“打印(1)…”,单元8数组内容);
那.setState({text:“Hi America”});
log(that.state.text);
setState({pdfFiles:[…that.state.pdfFiles,unit8Array_3;]});
});
};//sumbit事件的结束
render(){
返回(
import React, { Component } from "react";
class Addressbar extends Component {
render() {
return (
<nav className="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
<ul className="navbar-nav px-3">
<li className="nav-item text-nowrap d-none d-sm-none d-sm-block">
<small className="text-white">
<span id="account">
{"Your account address: " + this.props.account}
</span>
</small>
</li>
</ul>
</nav>
);
}
}
export default Addressbar;
import { Document, Page, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;