react-cropper URL 太长了

问题描述

我正在尝试使用 react-cropper 保存裁剪后的图像。它似乎按预期工作,但保存的 URL 疯狂 很长。单单数据包的控制台日志往往超过100kb,那只是一个数据URL。

当我控制台日志(并发送到数据库)时,我存储了一个data:image/png;base64,iVBORw0... 开头的值,然后持续很长时间,我需要大约 20 秒才能在我的 IDE 中滚动到它的末尾。>

我注意到这也是 code sandbox from the official docs 中的一个问题。

我直接从那个演示中获取了我的代码,但为了方便起见,我也将其粘贴在这里

export const CropperWidget = ({ userPhoto }) => {
  const [image,setimage] = useState(userPhoto);
  const [cropData,setCropData] = useState("");
  const [cropper,setCropper] = useState();

  const onChange = (e) => {
    e.preventDefault();
    let files = e.target.files;
    const reader = new FileReader();
    reader.onload = () => {
      setimage(reader.result);
    };
    reader.readAsDataURL(files[0]);
  };

  const getCropData = () => {
    if (typeof cropper !== "undefined") {
      setCropData(cropper.getCroppedCanvas().toDataURL());
    }
  };

  useEffect(() => {
    if (cropData) {
      postimage(cropData);
    }
  });

  return (
    <div>
      <br />
      <div>
        <input type="file" onChange={onChange} />
        <br />
        <br />
        <Cropper
          style={{ height: 400,width: 400 }}
          initialAspectRatio={1}
          preview=".img-preview"
          src={image}
          viewmode={1}
          guides={true}
          minCropBoxHeight={10}
          minCropBoxWidth={10}
          background={false}
          responsive={true}
          autoCropArea={1}
          checkOrientation={false} // https://github.com/fengyuanchen/cropperjs/issues/671
          onInitialized={(instance) => {
            setCropper(instance);
          }}
        />
      </div>
      <button onClick={getCropData}>Crop Image</button>
      <br />
    </div>
  );
};

解决方法

将数据发送到服务器,将其转换为二进制文件,将其存储在某处(例如您服务器的硬盘或 Amazon S3),为其提供一个 HTTP URL,然后在将来使用该 HTTP URL。