Last active
September 29, 2024 15:43
-
-
Save qnxdev/32340e22c5804dfbc8968330b81eb188 to your computer and use it in GitHub Desktop.
Storing image in localStorage in React
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 { useEffect } from "react"; | |
export default function SetImage() { | |
const saveImage = (e) => { | |
const file = e.target.files[0]; | |
const reader = new FileReader(); | |
reader.onloadend = () => { | |
// convert file to base64 String | |
const base64String = reader.result | |
.replace("data:", "") | |
.replace(/^.+,/, ""); | |
// store file | |
try{ | |
localStorage.setItem("pic", base64String); | |
} | |
catch(e){ | |
console.log(e) | |
} | |
document.getElementById( | |
"display" | |
).src = `data:image/png;base64,${base64String}`; | |
}; | |
reader.readAsDataURL(file); | |
}; | |
useEffect(() => { | |
if (localStorage) { | |
const base64String = localStorage.getItem("pic"); | |
document.getElementById( | |
"display" | |
).src = `data:image/png;base64,${base64String}`; | |
} | |
}); | |
return ( | |
<div> | |
<input type="file" id="file" onChange={saveImage} /> | |
<img src="" id="display" width="200px" /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment