4

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.

2 Answers 2

6

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)
    })
}
Sign up to request clarification or add additional context in comments.

1 Comment

better to copy code to answer, github content may change later
5

I suggest using the addAll method.

Here is the rough example :

  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,
    })
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.