【问题标题】:Upload a full directory to IPFS using ipfs (js-ipfs-http-client)使用 ipfs (js-ipfs-http-client) 将完整目录上传到 IPFS
【发布时间】:2019-12-16 05:22:38
【问题描述】:

我想使用 (js-ipfs-http-client) 模块将目录上传到浏览器上的 ipfs。

我发现了这个老问题。 https://github.com/ipfs/js-ipfs/issues/277 所以我决定用递归的方式添加文件,只得到一个哈希。

ipfs.addFromFs('path', { recursive: true, ignore: ['subfolder/to/ignore/**'] }, (err, result) => {
            if (err) { throw err }
            console.log(result)
        })

但它给了我这个错误。 fs Add doesn't work on browser

我需要使用 javascript 将目录上传到 ipfs,但我发现的所有资源只上传一个文件。或者很多带有哈希数组的文件。我需要一种方法来上传目录的所有文件并仅使用一个哈希来获取。提前致谢。

【问题讨论】:

    标签: javascript node.js ipfs


    【解决方案1】:

    Yehia,我相信您正在寻找的答案是https://github.com/ipfs/js-ipfs-http-client/blob/master/examples/upload-file-via-browser/src/App.js#L29-L67

    // Example #1
    // Add file to IPFS and return a CID
    saveToIpfs (files) {
      let ipfsId
      this.ipfs.add([...files], { progress: (prog) => console.log(`received: ${prog}`) })
        .then((response) => {
          console.log(response)
          ipfsId = response[0].hash
          console.log(ipfsId)
          this.setState({ added_file_hash: ipfsId })
        }).catch((err) => {
          console.error(err)
        })
    }
    
    // Example #2
    // Add file to IPFS and wrap it in a directory to keep the original filename
    saveToIpfsWithFilename (files) {
      const file = [...files][0]
      let ipfsId
      const fileDetails = {
        path: file.name,
        content: file
      }
      const options = {
        wrapWithDirectory: true,
        progress: (prog) => console.log(`received: ${prog}`)
      }
      this.ipfs.add(fileDetails, options)
        .then((response) => {
          console.log(response)
          // CID of wrapping directory is returned last
          ipfsId = response[response.length - 1].hash
          console.log(ipfsId)
          this.setState({ added_file_hash: ipfsId })
        }).catch((err) => {
          console.error(err)
        })
    }
    

    【讨论】:

    • 最好复制代码来回答,github内容以后可能会改变
    【解决方案2】:

    我建议使用addAll method

    这是一个粗略的例子:

      const addedFiles: AddedFiles[] = []
      for await (const file of ipfsClient.addAll(
        globSource(path, '**/*', {
          hidden: true,
        }),
        { ...ipfsOptions, fileImportConcurrency: 50 }
      )) {
        addedFiles.push({
          cid: file.cid.toString(),
          path: file.path,
          size: file.size,
        })
      }
    

    【讨论】:

    • 谢谢兄弟,这正是我需要的。
    猜你喜欢
    • 2022-07-01
    • 2021-11-26
    • 2021-06-30
    • 1970-01-01
    • 2021-03-12
    • 2020-10-20
    • 2019-03-13
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多