gpt4 book ai didi

javascript - 如何保存转换为base64的变量的值?

转载 作者:行者123 更新时间:2023-12-01 15:26:41 25 4
gpt4 key购买 nike

我正在使用具有数千个地理坐标并转换为 base64 的 .zip 文件。
我可以将文件转换为base64,问题是保存这个变量的结果以备后用。
我正在尝试使用 setState保存变量的值,但没有任何 react 。
你能告诉我我做错了什么吗?
这是我输入的代码 codesandbox
here我正在转换的 zilFile

  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);
};

enter image description here

最佳答案

我已经这样修复了,它工作得很好,请看看。

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>
);
}
或者如果你想使用 zip 文件,你可以使用 useEffect 检查加载的状态并调用 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);
};

关于javascript - 如何保存转换为base64的变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63844863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com