繁体   English   中英

如何在react-dropzone中将图像转换为base64?

[英]How to convert image to base64 in react-dropzone?

我正在尝试在我的应用程序上实现 react-dropzone,但我无法发布并始终收到Internal Server Error ,并且错误: TypeError: argument should be a bytes-like object or ASCII string, not 'list' in case data帖子必须使用转换base64

这是我的 onDrop 功能

onDrop(uploadData) {
  this.setState({
    uploadData,
  });
}
onDropHandler(uploadData) {
  var uploadData = uploadData[0];
  const reader = new FileReader();
  reader.readAsDataURL(uploadData);
  reader.onload = event => {
    this.setState({
      uploadData: this.state.uploadData([{ base64: event.target.result }]),
    });
  };
  reader.readAsDataURL(uploadData);
}

这是我的渲染方法:

<div className="dropzone">
  <Dropzone
    onDrop={this.onDrop.bind(this)}
    accept="image/jpeg, image/png, image/jpg"
    onDrop={uploadData => {
      this.setState({ uploadData });
    }}
    maxSize={200000}
    multiple={false}
  >
    <p>Maksimal 2 MB (JPG/PNG)</p>
  </Dropzone>
  {this.state.uploadData.map(f => (
    <span key={f.name}>
      {f.name} - {f.size} bytes
    </span>
  ))}
</div>

这是提交后的错误图片

这是提交后的json图片

也许这可能有用

    const handleDrop = React.useCallback((acceptedFiles) => {
      const file = acceptedFiles.find(f => f)
      let reader = new FileReader()

      reader.readAsDataURL(file)
      reader.onload = () => {
        console.log({
          src: file.preview,
          data: reader.result
        })
        setB64(reader.result)
       }

     }, []);

其中setB64是 React useState Hook

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM