How to upload files on IPFS infura.io using React.
Tags: blockchain, web3, react, ipfs
Published: 2022-08-20 06:15:16

**After infura has depreciated the public gateway lots of developers face issues while uploading files on the IPFS infura.**

Things we are going to do.

- we will create and setup our infura account 
- we will upload files on IPFS 
- we access content from the IPFS.

## Setting up the infura account.
Go to the official website [infura.io](https://infura.io/) and create a new account if you don't have it after creating and signing it click on the **create new key**.
![Dashboard of the infura](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v7eetvoy1l27gnbzgbei.png)

Select the network IPFS and mention name of the Project whatever you want and create it.

![a card showing a options to select network and name of the project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29pf0mg54scrfpfo49ae.png)

After you will see following credential here project secret key , API Key secret and IPFS endpoint one more thing we want here is dedicated gateway domain link so we will get it by enabling the dedicated gateway option enter the name of the domain on your own choice and save the domain.

![image showing the project summary.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kpxftaoye6tcfyu1a5qu.jpg)

now you have setup your account and now you have your own dedicated gateway we will use all these credential in our project later on.

## How to Upload files on IPFS in your project.
In your React project we need npm package called ipfs-http-client install it using this command.

`npm i ipfs-http-client`

Open App.js file in your react project and import the ipfs-http-client we are importing `create` function as `ipfsHttpClient` provided by the `ipfs-http-client` and set up your infura credential in your react project.

`import { create as ipfsHttpClient } from "ipfs-http-client";
`
add up your infura keys in your App.js component we will use them to generate the authorization key by generating the `base64` key using the function `btoa`



```
const projectId = "<YOUR PROJECT ID>";
const projectSecret = "<YOUR PROJECT SECRET>";
const authorization = "Basic " + btoa(projectId + ":" + projectSecret);

```

_Note: feel free to use environment variable for the safer alternative_

Now we will create a variable `ipfs` this will store the ipfs http client return by the `create` function. we are going to pass the argument in `create` function include `url` and the `headers` include `authorization`

```
   const ipfs = create({
      url: "https://ipfs.infura.io:5001/api/v0",
      headers:{
        authorization
      }
    })
```

after established the connection with **IPFS** we will upload files from our input form.

```
    <div className="App">
      {ipfs && (
        <>
          <h3>Upload file to IPFS</h3>
          <form onSubmit={onSubmitHandler}>
            <input type="file" name="file"/>
            <button type="submit">Upload file</button>
          </form>
        </>
      )}
    </div>
```
`onSubmitHandler` is the main function which will take care of all the implementation lets write the code.
```
const onSubmitHandler = async (event) => {
    event.preventDefault();
    const form = event.target;
    const files = (form[0]).files;
  
    if (!files || files.length === 0) {
      return alert("No files selected");
    }
  
    const file = files[0];
    // upload files
    const result = await ipfs.add(file);
  
    setImages([
      ...images,
      {
        cid: result.cid,
        path: result.path,
      },
    ]);
  
    form.reset();
  };
```
Logic of this function is straight forward

1. Verify the file if selected otherwise show the alert message file is not selected

2. `ipfs.add(file)` is uploading file to IPFS

3. `add` method returns the following properties include `cid` , `path` , `size` and `mtime` the most important properties are `cid` (it is the content identifier or unique content identifer given to the uploaded files) and `path`(which we will use to display files). 
 
4. we will update the state of the images by adding the new files

add this line in the beginning of the component.

```
    const [images, setImages] = useState([])

```
  

## Displaying the uploaded files from the IPFS

We have our logic already implemented in the onSubmitHandler function now we are going to use this logic in our jsx
lets add the template to display the files and one more thing todo in the last copy the dedicated gateway domain link from the Infura API key and replace it with the `dedicated-gateway-link`.

```
<div>
        {images.map((image, index) => (
          <img
          alt={`Uploaded #${index + 1}`}
          src={"<dedicated-gateway-link>/ipfs/" + image.path}
            style={{ maxWidth: "400px", margin: "15px" }}
            key={image.cid.toString() + index}
          />
        ))}
      </div>
```
Now we have succussfully implemented all the things you can check the complete code in this [Github repo](https://github.com/Sameer-472/Infura-ipfs-storage).
![final result of the project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sqj9q41weelcitcm5h3w.png)



## Conclusion
You have learned how to setup a infura project upload files and access it in your React application. However IPFS innovative concept of being a decentralized solution to store files using a peer-to-peer storage network.