【问题标题】:How to convert image to base64 in react-dropzone?如何在 react-dropzone 中将图像转换为 base64?
【发布时间】:2018-10-19 09:52:28
【问题描述】:

我正在尝试在我的应用程序上实现 react-dropzone,但我无法发布并且总是得到 Internal Server Error,并且错误:TypeError: argument should be a bytes-如对象或 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

【问题讨论】:

  • 请在您的问题中以文本形式包含错误消息。包括完整的回溯。并且还包括整个 react 类,而不仅仅是一些方法。 this.state.uploadData 这里是什么?好像是一个函数?为什么你的州有一个功能? minimal reproducible example

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


【解决方案1】:

也许这很有用

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

【讨论】:

    猜你喜欢
    • 2022-08-12
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 2019-07-12
    • 2021-11-09
    相关资源
    最近更新 更多