DEV Community

Cover image for Send Files to IPFS using Pinata API in ReactJS
Fidal Mathew
Fidal Mathew

Posted on

Send Files to IPFS using Pinata API in ReactJS

Hi fellow readers, I hope you’re doing good. Web3 is an amazing space and every day there is something new to learn no matter how experienced you are. In this article, I’m gonna talk about how we can upload files to IPFS using Pinata API.

Before moving on, let's talk a little about IPFS. IPFS/ InterPlanetary File System is a protocol and peer-to-peer network for storing and sharing data in a distributed file system. Many companies provide this service, for example: Pinata, which we’re gonna work on in this article.

First, to work with Pinata IPFS, create an account on Pinata. We need API keys to work with their API. Therefore, in the top right corner, click on the profile option and click on the API Keys option.

API key

Now, keep the Admin option on because you’d like to pin files to the IPFS and enter any name you’d like. It will now generate a new API_KEY along with a SECRET_KEY. Store both the details in a ".env.local" file present at the root of the React App folder as:



REACT_APP_PINATA_API_KEY=<your api key>
REACT_APP_PINATA_API_SECRET=<your secret key>


Enter fullscreen mode Exit fullscreen mode

Make sure to install dotenv npm package using: npm i dotenv

So, let's define a useState hook to manage the content of the file.



    const [fileImg, setFileImg] = useState(null);


Enter fullscreen mode Exit fullscreen mode

Note: Don’t forget import {useState} from ‘react’;

The next thing we need is a function to check whether we are having an empty file, if not we will be sending that file using the Pinata API.



    const sendFileToIPFS = async (e) => {

        if (fileImg) {
            try {

                const formData = new FormData();
                formData.append("file", fileImg);

                const resFile = await axios({
                    method: "post",
                    url: "https://api.pinata.cloud/pinning/pinFileToIPFS",
                    data: formData,
                    headers: {
                        'pinata_api_key': `${process.env.REACT_APP_PINATA_API_KEY}`,
                        'pinata_secret_api_key': `${process.env.REACT_APP_PINATA_API_SECRET}`,
                        "Content-Type": "multipart/form-data"
                    },
                });

                const ImgHash = `ipfs://${resFile.data.IpfsHash}`;
             console.log(ImgHash); 
//Take a look at your Pinata Pinned section, you will see a new file added to you list.   



            } catch (error) {
                console.log("Error sending File to IPFS: ")
                console.log(error)
            }
        }
    }


Enter fullscreen mode Exit fullscreen mode

Finally, let's define what we’re gonna return. We are calling a function sendFiletoIPFS() when the form is submitted, and the value of the file is gonna be e.target.files[0].



return(
<form onSubmit={sendFileToIPFS}>
<input type="file" onChange={(e) =>setFileImg(e.target.files[0])} required />
<button type='submit' >Mint NFT</button>            
</form>
)


Enter fullscreen mode Exit fullscreen mode

You can learn more about how to send JSON data, remove files from IPFS, etc in the API documentation by Pinata.
I hope you learned how to send files to Pinata IPFS in a React Application. If you have any queries, feel free to connect with me on:

If you want to mint an NFT with IPFS API, you can take a look at my project page here:
https://github.com/FidalMathew/Voting_system_blockchain/blob/main/client-votingSystem/src/SendNft.jsx

Till then, keep hacking!😊

Top comments (7)

Collapse
 
joshuajee profile image
Joshua Evuetapha

Should the pinata endpoint be called from the frontend? Or backend?

Collapse
 
fidalmathew profile image
Fidal Mathew

Since, Pinata is typically used for blockchain projects, it doesn't have a backend server. Nevertheless, I would recommend using it at the frontend rather than backend. It's your choice, it's just an API call.

Collapse
 
joshuajee profile image
Joshua Evuetapha

Alright, i was just worried that the API keys could be abused by a malicious user on the frontend

Thread Thread
 
fidalmathew profile image
Fidal Mathew

That's a point, but you can store it using .env files even at frontend.

Thread Thread
 
joshuajee profile image
Joshua Evuetapha

They would still be available on the client side

Collapse
 
glitchflex profile image
Pratyugna Manna

Before uploading the file we need to convert into a binary format... How do we do that

Collapse
 
gauragastya profile image
Agastya gaur

how to delete it using above code