Adding a file while preserving filename using js-ipfs

If you want to preserve file name, you need to wrap it in a directory.

Until wrapWithDirectory flag lands in js-ipfs (PR is merged, but not released yet) you can do it manually by adding a named file link to an empty unixfs-dir via object.patch.addLink API.

In command line, it looks like this:

ipfs object patch add-link <root_CID> <file_name> <file_CID> - Add a link to a given object

We know that QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn is the CIDv0 of an empty dir, so all you really need is one command:

$ ipfs object patch QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn add-link bug_or_feature.jpg Qmayz4F4UzqcAMitTzU4zCSckDofvxstDuj3y7ajsLLEVs

Example above returns QmVnLkRxWWv2xiPKeQy6re1zCepzX7YXUiq5fESkd1j8bC – a new CID representing a wrapping directory with one file:

https://ipfs.io/ipfs/QmVnLkRxWWv2xiPKeQy6re1zCepzX7YXUiq5fESkd1j8bC/
https://ipfs.io/ipfs/QmVnLkRxWWv2xiPKeQy6re1zCepzX7YXUiq5fESkd1j8bC/bug_or_feature.jpg

JS-IPFS API is here. Hope this helps.

1 Like