DEV Community

Rajiv Chaulagain
Rajiv Chaulagain

Posted on

7 1

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.

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>
 )
};
Enter fullscreen mode Exit fullscreen mode

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>
)
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (1)

Collapse
 
nyashu profile image
Yashu Neupane

nice

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay