如何在React-Dropzone中将图像转换为Base64?

3
我正在尝试在我的应用程序中使用react-dropzone,但是我无法发布并且总是收到“内部服务器错误”的错误提示,错误提示为:“TypeError:参数应该是类似字节的对象或ASCII字符串,而不是'list'”,如果数据发布必须使用转换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图片


请在您的问题中将错误消息作为文本包含在内。包括完整的回溯。还要包括整个React类,而不仅仅是一些方法。这里的this.state.uploadData是什么?看起来它是一个函数?为什么你的状态中有一个函数?[mcve] - Håken Lid
1个回答

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 Hook


使用这种方法时出现错误:Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. - Junaid Nazir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接