Created
May 10, 2022 08:41
-
-
Save tamalchowdhury/72e0c5d4209da095acd59fca238338c3 to your computer and use it in GitHub Desktop.
Upload image in the client using Base64 strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from "react" | |
/** | |
* Takes a file from the file browser and | |
* converts into a base64 string | |
* Shows an alert when the file type does not match | |
* Function is outside so it can be portable | |
* @param {Blob} file | |
* @returns {Promise} | |
*/ | |
function getBase64(file) { | |
return new Promise((resolve, reject) => { | |
const reader = new FileReader() | |
const allowedTypes = ["image/jpeg", "image/jpg", "image/png", "image/gif"] | |
if (!allowedTypes.includes(file.type)) { | |
window.alert("Only jpg & png image files are allowed!") | |
return | |
} | |
reader.readAsDataURL(file) | |
reader.onload = () => resolve(reader.result) | |
reader.onerror = (error) => reject(error) | |
}) | |
} | |
export default function App() { | |
// thumb is the base64 converted string | |
const [thumb, setThumb] = useState(undefined) | |
// Handles the upload event | |
const handleUpload = (event) => { | |
getBase64(event.currentTarget.files[0]).then((imageData) => { | |
return setThumb(imageData) | |
}) | |
} | |
return ( | |
<> | |
<form> | |
<label htmlFor="image">Upload the image</label> | |
<input type="file" name="image" id="image" onChange={handleUpload} /> | |
</form> | |
{/* shows the image when it's set in the state... */} | |
{thumb && <img src={thumb} width={300} />} | |
</> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment