I am using a .zip file with thousands of geographical coordinates and converting to base64.
I can convert the file to base64, the problem is to save the result of this variable for later use.
I'm trying to use setState
to save the variable's value but nothing happens.
Can you tell me what I'm doing wrong?
Here's my code I put in codesandbox
And here the zilFile I'm converting
const [zipFile, setZipFile] = useState("");
const [base64, setBase64] = useState("");
const getBase64 = (file, cb) => {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
cb(reader.result);
};
reader.onerror = function (error) {};
};
const toBase64 = async () => {
let auxZip = "";
await getBase64(zipFile, (result) => {
auxZip = result.substring(28);
console.log("auxZip: ", auxZip);
setBase64(auxZip);
});
};
const onSave = () => {
toBase64();
console.log("base64: ", base64);
};
const handleZipChangle = (event) => {
const file = event.target.files[0];
setZipFile(file);
};
I have fixed like this, it worked perfectly, please take a look.
import React, { useState } from "react";
import "./styles.css";
import FormControl from "@material-ui/core/FormControl";
import Typography from "@material-ui/core/Typography";
export default function App() {
const [base64, setBase64] = useState("");
const getBase64 = (file, cb) => {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = (e) => {
cb(e.target.result);
};
reader.onerror = function (error) {};
};
const onSave = () => {
console.log("base64: ", base64);
};
const handleZipChangle = (event) => {
const file = event.target.files[0];
let auxZip = "";
getBase64(file, (result) => {
auxZip = result.substring(28);
setBase64(auxZip);
});
};
return (
<div className="App">
<FormControl>
<Typography>Select Zip File:</Typography>
<input
accept="zip/*"
type="file"
id="contained-button-file"
onChange={handleZipChangle}
/>
</FormControl>
<div style={{ marginTop: "30px" }}>
<button onClick={onSave}>SAVE</button>
</div>
</div>
);
}
or if you want to use zip file, you can use useEffect to check the state loaded and call getBase64
useEffect(() => {
let auxZip = "";
zipFile &&
getBase64(zipFile, (result) => {
auxZip = result.substring(28);
setBase64(auxZip);
});
}, [zipFile]);
const onSave = () => {
console.log("base64: ", base64);
};
const handleZipChangle = (event) => {
const file = event.target.files[0];
setZipFile(file);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With