Search code examples
javascriptnode.jsipfs

Upload a full directory to IPFS using ipfs (js-ipfs-http-client)


I want to upload a directory to ipfs on my browser using (js-ipfs-http-client) module.

I found this old issue. https://github.com/ipfs/js-ipfs/issues/277 So I decided to use recursive way to add files and get only one hash for it.

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

But it gave me this error. fs Add doesn't work on browser

I need to upload a directory to ipfs using javascript but all resources I had found upload only one file.Or a lot of files with array of hashes. I need a way to upload all files of directory and get the with only one hash. Thanks in advance.


Solution

  • Yehia, I believe the answer you are looking for is at 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)
        })
    }