DEV Community

es404020
es404020

Posted on

File Upload in Next js

As easy as file upload my sound to mid level or senior developer, junior developer still struggle to implement file upload without having to use the default input tag for file upload .In this tutorial we would learn how to implement file upload on a button click with next.js and Chakara UI.

Step 1:

 <input type="file"
                  ref={hiddenFileInput}
                  onChange={handleChange}

                  accept="image/*"
                  style={{ display: 'none' }} />


<IconButton onClick={handleClick} size="xx-small" pos="absolute" zIndex="10" left="5px" bottom="5px"
 aria-label="file upload " icon={<BiCloudUpload />} />

Enter fullscreen mode Exit fullscreen mode

Step 2:

We have to create an input filed with a style display to none. This helps us hide the input tag.

  const hiddenFileInput = useRef(null);

  const handleChange = event => {

    if (event.target.files && event.target.files[0]) {
      const i = event.target.files[0];
      const body = new FormData();
      body.append("image", i);


    }
  };


  const handleClick = event => {
    hiddenFileInput.current.click();
  };

Enter fullscreen mode Exit fullscreen mode

Using the react useRef hook as a reference on the input tag we can access the content of tag .

Calling the handleClick helps call a click event on the invisible input tag giving us the chances to pick a file for upload.

The handleChange help to listern to change on the input tag. When handling file upload it is important to use FormData() if you intend to store on a server.

Thanks for reading .

Discussion (0)