首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用IPFS将图像上传到ipfs http-client

无法使用IPFS将图像上传到ipfs http-client
EN

Ethereum用户
提问于 2021-09-17 10:45:57
回答 1查看 2.7K关注 0票数 1

在从ipfs-http-client转到ipfs-api之后,我在上传图片到IPFS时遇到了问题。目前,我的页面代码是这样的:

代码语言:javascript
复制
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

这些图像应该通过智能契约函数保存到区块链中,并且应该显示在另一个页面上,如下所示:

代码语言:javascript
复制
// other code
<li className="list-group-item">
    <img src={ `https://ipfs.io/ipfs/${review.ipfsHash}` } alt="" />
</li>

这就是ipfs.js的样子:

代码语言:javascript
复制
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中。

EN

回答 1

Ethereum用户

回答已采纳

发布于 2021-09-18 14:54:01

我找到了解决问题的办法!

对于ipfs-http-client,您需要使用ipfs.add作为async/await函数的一部分,这样ipfs.add才能真正执行。如果不使用async/await函数,当getHash()运行时,它什么也不做。

我就是这样改变getHash()的:

代码语言:javascript
复制
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
    }
}
票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/110104

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档