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

时间:2018-05-09 10:04:40

标签: javascript reactjs base64 dropzone.js react-dropzone

我尝试在我的应用上实施react-dropzone,但我无法发布并始终获得内部服务器错误,并且错误: TypeError:参数应该是一个类似字节的对象或ASCII字符串,而不是' list' 以防数据帖子必须使用convert 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>

This is error pic after submit

and this is json pic after submit

1 个答案:

答案 0 :(得分:0)

也许这很有用

    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 钩子