Upload an image and transform it into base64 in React

Create a FileReader() object and use readAsDataURL() function to read an image and transform it into base64:

jsx
import React, { useState } from 'react';

const Upload = () => {

    const [src, setSrc] = useState(null);

    const uploadPic = (e) => {

        let file = e.target.files[0];

        let reader = new FileReader();

        reader.readAsDataURL(file);

        reader.onload = () => setSrc(reader.result);

    }

    return(
        <div className = 'Upload'>
            <input type = 'file' onChange = {uploadPic} accept = 'image/*'/>
            <img src = {src}/>
        </div>
    );

}

export default Upload;

Optional tips

  1. Add accept = 'image/*' to accept only images.
  2. Additionally, you could add a resize function to scale the uploaded image.

Example:

javascript
const resizeMe = (img, maxWidth) => {

    let canvas = document.getElementById('background');
    let ctx    = canvas.getContext('2d');

    canvas.width  = maxWidth;
    canvas.height = maxWidth * (img.height/img.width);

    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    
    return canvas.toDataURL("image/jpeg", 0.7); 
    
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.