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

vbe*_*nal 5 javascript reactjs

我正在使用具有数千个地理坐标并转换为 base64 的 .zip 文件。

我可以将文件转换为base64,问题是保存这个变量的结果以备后用。

我试图用来setState保存变量的值,但没有任何反应。

你能告诉我我做错了什么吗?

这是我放在codeandbox 中的代码

这里的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);
  };
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Cuo*_*Van 1

我已经这样修复了,效果很好,请看一下。

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

或者如果你想使用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);
  };
Run Code Online (Sandbox Code Playgroud)