Reading JSON/Image input file in React

Ravi Shankar
2 min readSep 6, 2020

--

Upload file/image

To read the content in the file, we need to use FileReader API.

⭐️ Reading file onChange:

  • During onChange/onupload of input file tag, we will pass the file to changeHandler called readFileOnUpload.
<input type="file"
onChange={(e)=>readFileOnUpload(e.target.files[0])} />

The changeHandler function is described as follows 👇.

const readFileOnUpload = (uploadedFile) =>{
const fileReader = new FileReader();
fileReader.onloadend = ()=>{
try{
setData(JSON.parse(fileReader.result));
setErrorData(null)
}catch(e){
setErrorData("**Not valid JSON file!**");
}
}
if( uploadedFile!== undefined)
fileReader.readAsText(uploadedFile);
}
  • Here, with the fileReader, we check whether file is present and then use fileReader.readAsText() method to read the content in the file.

Once the file has been started reading, onloadstart, onprogess and onloadend properties are triggered in the exact order.

  • After the file is read, we use onloadend property to set data in our state variable.
  • If the content is not JSON, then the catch block gets executed which sets the error message.

⭐️Reading an image file:

In some situations, we may want to read an image, when the user uploads the image and decides to view as preview option. In that case, we need to use fileReader.readAsDataURL(uploadedFile) instead of readAsText() method.

This method tells fileReader that the input element is an image. In addition, we need to check whether image is only uploaded. Else error message should be displayed.

So, rewriting the fileOnUpload method 👇,

fileReader.onloadend=(onFileReadEndEvent)=>{
const image = new Image();
image.src = onFileReadEndEvent.target.result;
image.onload = () =>{
setData(onFileReadEndEvent.target.result)
setErrorData(null);
}
image.onerror = ()=>{
setErrorData("Not valid Image!");
setData(null);
}
}
if( uploadedFile!== undefined)
fileReader.readAsDataURL(uploadedFile);

If we want to show general loading bar when uploading large files, we can use fileReader.onloadstart property to set the loading bar.

onloadstart = function(event) {
ShowLoadingBar(true);
};
fileReader.onprogress = (event) =>{
if (event.loaded && event.total) {
const percent = (event.loaded / event.total) * 100;
console.log(`Progress: ${Math.round(percent)}`);
}
}

⭐️Handling using Refs:

  • Sometimes we need to read the data only when specific action is made, such as onClick of a button or onSubmit of form.
const fileRef = useRef(null);
<form onSubmit={(e)=>{readFileWhenSubmit(e)}}>
<input type="file" ref={fileRef}/>
<button >Display File Content</button>
</form>
  • Here , ref is used to store the reference of the file input node present in actual DOM.

The execution of readFileWhenSubmit() method is as follows 👇.

const readFileWhenSubmit = (event) =>{
event.preventDefault();
// get file using ref
const uploadedFile = fileRef.current.files[0];
const fileReader = new FileReader();
// Rest same as above
}

If you find it useful, please leave claps! 👏

--

--