I have form with 4 pages , written in react. when I am clicking on next page the form data of this page are saved in sessionStorage and move to next page. so that if I am returning the previous page the form takes its values from the storage. My problem is with the pictures. I upload an image in an input that accepts image files. and saves it in storage after converting to base64.
The problem is that when I go back, I can't get the image to be displayed in the input. (And don't send the photo in axios after I get to the last page) I would very much appreciate your answers. here I am setting the image:```
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
sessionStorage.setItem("deceasedPhoto", base64data)
resolve(base64data)
};
});
};
const handleChange = function loadFile(event) {
if (event.target.files.length > 0) {
const file = URL.createObjectURL(event.target.files[0]);
getBase64FromUrl(file)
setFile({
url: file,
file: event.target.files[0],
name: event.target.files[0].name,
});
}
};
<>
<label htmlFor="icon-button-file">
<Input
accept="image/*"
onChange={handleChange}
file={file.file}
id="icon-button-file"
type="file"
sx={{ display: "none" }}
/>
<IconButton
sx={{ bgcolor: "#000000", m: 0 }}
aria-label="upload picture"
component="span"
>
<PhotoCamera
sx={{ color: "#ffffff", height: 12, width: 12, p: 0 }}
/>
</IconButton>
</label>
and here how I try to get it in useffect hook when page mounted:`
const [file, setFile] = useState({ url: "", file: "", name: "" });
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
}
useEffect(() => {
if (sessionStorage.getItem("deceasedPhoto")) {
var file = dataURLtoFile(sessionStorage.getItem("deceasedPhoto"), 'hello.png');
setFile({ url: "", file: file, name: "" })
}
}, [])
````your text`