在从ipfs-http-client转到ipfs-api之后,我在上传图片到IPFS时遇到了问题。目前,我的页面代码是这样的:
import ipfs from "../utils/ipfs";
export default function NewReview() {
const [ipfsHash, setIpfsHash] = useState("");
const [buffer, setBuffer] = useState(null);
const [isFile, setFile] = useState(null);
function getHash() {
ipfs.files.add(Buffer.from(buffer), (error, result) => {
if (error) {
console.error(error)
return
}
setIpfsHash(result[0].hash);
});
}
useEffect(() => {
if (buffer) {
getHash()
}
});
const captureFile = (event) => {
if (event.target.files[0]) {
event.preventDefault();
setFile(URL.createObjectURL(event.target.files[0]));
const reader = new FileReader();
reader.readAsArrayBuffer(event.target.files[0])
reader.addEventListener("load", () => {
setBuffer(reader.result)
})
}
}
// skipping a bit to where the image is uploaded
<div>
<img src={isFile} alt="" style={{ maxWidth: '400px' }} />
<input type="file" onChange={captureFile} />
</div>
// I don't think the rest is relevant这些图像应该通过智能契约函数保存到区块链中,并且应该显示在另一个页面上,如下所示:
// other code
<li className="list-group-item">
<img src={ `https://ipfs.io/ipfs/${review.ipfsHash}` } alt="" />
</li>这就是ipfs.js的样子:
const { create } = require('ipfs-http-client');
const ipfs = create({host: 'ipfs.infura.io', port: 5001, protocol: 'https'});
export default ipfs;当我使用ipfs-api时,上面的代码就可以工作了。但是,对于ipfs-http-client,我不能使用ipfs.files.add,因为我得到了一个TypeError: default.files.add is not a function错误。
我尝试过用ipfs.files.add替换ipfs.add,但这是行不通的,即使我将缓冲区放在JavaScript对象中,就像ipfs.add文档所表明的那样。当我查看控制台时,我甚至没有收到任何错误消息,只是它似乎不起作用,而且ipfsHash只是一个空字符串(与原始状态一样)。
我非常感谢你的想法和建议!如果控制台中没有任何错误,我就不知道是什么错误,也不知道如何让ipfs-http-client像我的代码那样成功地将图像文件保存到IPFS中。
发布于 2021-09-18 14:54:01
我找到了解决问题的办法!
对于ipfs-http-client,您需要使用ipfs.add作为async/await函数的一部分,这样ipfs.add才能真正执行。如果不使用async/await函数,当getHash()运行时,它什么也不做。
我就是这样改变getHash()的:
async function getHash() {
try {
const uploadResult = await ipfs.add(Buffer.from(buffer))
setIpfsHash(uploadResult.path)
} catch(e) {
console.log(e)
toast.error(e.message)
return
}
}https://ethereum.stackexchange.com/questions/110104
复制相似问题