Mutable File System | Lesson 4 of 11

Add a file to MFS

Now that we have files accessible in the browser, let's see how to add them to IPFS.

To add a file to IPFS, we can use the MFS files.write method like so:

await ipfs.files.write(path, content, [options])

The MFS files.write method can accept file content in the form of a Buffer, ReadableStream, PullStream, Blob (only in the browser), or string path to a file (only in Node.js). Since file objects in the browser are a kind of Blob, we're good to go!

Even though the file object in the browser happens to know its own filename, Blobs in general don't, so IPFS can't determine the existing filename directly. We'll have to provide the desired filename as part of the path.

The path is a new path you'd like to create within your IPFS instance, including the desired filename. (Note that it's the destination path we're describing, not the path where the file already resides on your computer.)

The MFS files.write method, like similar methods you may have used on your own computer, is actually built for editing the content of an existing file. However, we can also use it to create a brand new file by providing the boolean option { create: true } to indicate that a file should be created at the given path if it doesn't already exist there.

So if we had a file object in our browser, accessible via a variable catPic, and we wanted to add it to our root directory on IPFS and have it be named cat.jpg, we could do it like so:

await ipfs.files.write('/cat.jpg', catPic, { create: true })

If we needed to, we could have used concatenation (the joining together of strings) to create that same path. This comes in handy if your filename is a property of your file object, as is true in the browser.

await ipfs.files.write('/' + catPic.name, catPic, { create: true })

Note that the files.write method does not provide a return value.

Later on we'll look at how to add files to directories other than the root directory.

Try it!

Let's add some files to IPFS using MFS. Since files is an array representing the files currently available to us in the browser, we'll need to loop through the array and use files.write to add each file we find there to IPFS, one at a time. (Only have a single file uploaded? No problem!)

Put your files in your root directory ( / ) and be sure to include the name of each file in the path when you add it. (Hint: The file object in the browser stores the filename as file.name). Be sure to set up your options so that a new file is created when one isn't found at the given path.

Step 1: Upload files
Step 2: Update code
View SolutionReplace with SolutionClear Default Code
Upload file(s) and update the code to complete the challenge.
You must upload a file before submitting.