Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 535
yehia tarek Avatar asked Jan 26 '23 23:01

yehia tarek


2 Answers

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)
    })
}
like image 164
David Dias Avatar answered Jan 29 '23 08:01

David Dias


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,
    })
  }
like image 41
woss Avatar answered Jan 29 '23 06:01

woss