How to upload image with base64 and validate it with formik

Lets upload image with formik and react js.

Now,Base64 is a group of binary-to-text encoding schemes that represent binary data (more specifically, a sequence of 8-bit bytes) in sequences of 24 bits that can be represented by four 6-bit Base64 digits….


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Rajiv Chaulagain

Lets upload image with formik and react js.

Now,Base64 is a group of binary-to-text encoding schemes that represent binary data (more specifically, a sequence of 8-bit bytes) in sequences of 24 bits that can be represented by four 6-bit Base64 digits.

Now we will create a single image .

const singleImage = () => {

 const convertToBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = () => {
        resolve(fileReader.result);
      };
      fileReader.onerror = (error) => {
        reject(error);
      };
    });
  };

  const handleIcon = async (e, setFieldValue) => {
    const file = e.target.files[0];
       //check the size of image 
    if (file?.size/1024/1024 < 2) {
      const base64 = await convertToBase64(file);
      setFieldValue('profile_image', base64);
    }
    else {
      toast.error('Image size must be of 2MB or less');
    };
  };

  return (
       <div className="mb-3 form-group">
          <label className="required">Upload Photo</label>
               <Field name='profile_image'>
                   {({ form, field }) => {
                     const { setFieldValue } = form
                        return (
                          <input
                            type="file"
                             className='form-control'
                              required
                          onChange={(e) => handleIcon(e, setFieldValue)}
                             />
                            )
                          }}
                     </Field>
                   <div className="text-danger">
               <ErrorMessage name="profile_image" />
         </div>
     </div>
 )
};

So, here formik handles the image and then we take the image from onchange function and check the size and if the size is less than the condition then , convertToBase64 function converts the image into base64 as string and hence the image is converted to base64.

const multipleImage = () => {

export const convertToBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = () => {
        resolve(fileReader.result);
      };
      fileReader.onerror = (error) => {
        reject(error);
      };
    });
  };

const handleProfile = async (e, setFieldValue) => {
    const file = e.target.files[0];
    if (file?.size / 1024 / 1024 < 2) {
        const base64 = await convertToBase64(file);
        setFieldValue('image', base64);
    }
    else {
        toast.error('Image size must be of 2MB or less');
    };

return (
          <div className="mb-3 form-group">
            <label>Upload Cover Photo</label>
            <Field name={name}>
                {({ form, field }) => {
                    const { setFieldValue } = form
                    return (
                        <input
                            type="file"
                            className='form-control'
                            onChange={(e) => handleProfile(e, setFieldValue)}
                        />
                    )
                }}
            </Field>
        </div>
)
}

Conclusion

Hence in the formik data we can find our image as converted to base64.


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Rajiv Chaulagain


Print Share Comment Cite Upload Translate Updates
APA

Rajiv Chaulagain | Sciencx (2022-10-15T06:08:07+00:00) How to upload image with base64 and validate it with formik. Retrieved from https://www.scien.cx/2022/10/15/how-to-upload-image-with-base64-and-validate-it-with-formik/

MLA
" » How to upload image with base64 and validate it with formik." Rajiv Chaulagain | Sciencx - Saturday October 15, 2022, https://www.scien.cx/2022/10/15/how-to-upload-image-with-base64-and-validate-it-with-formik/
HARVARD
Rajiv Chaulagain | Sciencx Saturday October 15, 2022 » How to upload image with base64 and validate it with formik., viewed ,<https://www.scien.cx/2022/10/15/how-to-upload-image-with-base64-and-validate-it-with-formik/>
VANCOUVER
Rajiv Chaulagain | Sciencx - » How to upload image with base64 and validate it with formik. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/10/15/how-to-upload-image-with-base64-and-validate-it-with-formik/
CHICAGO
" » How to upload image with base64 and validate it with formik." Rajiv Chaulagain | Sciencx - Accessed . https://www.scien.cx/2022/10/15/how-to-upload-image-with-base64-and-validate-it-with-formik/
IEEE
" » How to upload image with base64 and validate it with formik." Rajiv Chaulagain | Sciencx [Online]. Available: https://www.scien.cx/2022/10/15/how-to-upload-image-with-base64-and-validate-it-with-formik/. [Accessed: ]
rf:citation
» How to upload image with base64 and validate it with formik | Rajiv Chaulagain | Sciencx | https://www.scien.cx/2022/10/15/how-to-upload-image-with-base64-and-validate-it-with-formik/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.