【问题标题】:upload image file to state with react将图像文件上传到带有反应的状态
【发布时间】:2018-02-16 20:39:34
【问题描述】:

我正在尝试上传一张对此代码做出反应的图片

<input type="file" id="InputFile" accept="image/*" value={this.state.image} onChange={this.handelChangeImage} />

这就是状态

constructor(props) {
super(props);
this.state = {
    image: [],
}

this.handelChangeImage = this.handelChangeImage.bind(this);

}

这是绑定函数

handelChangeImage(event) {
   let image = event.target.files[0];
   let form = new FormData();
   form.append('image', image);
   this.setState({
       image: form,
   });

}

它给了我这个错误

未捕获的 DOMException:无法在“HTMLInputElement”上设置“value”属性:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串。

任何帮助!

【问题讨论】:

  • 我不熟悉使用 FormData() 将文件读入状态。如果您不介意使用新的 FileReader,那么我可以为您提供答案。

标签: image reactjs web upload


【解决方案1】:

我的错误在这里

<input type="file" id="InputFile" accept="image/*" value={this.state.image} onChange={this.handelChangeImage} />

我必须删除这个value={this.state.image}

【讨论】:

    【解决方案2】:

    看起来您没有正确读取文件,请尝试以下操作:

    handelChangeImage(event) {
      const reader = new FileReader();
      reader.onload = function(ee) {
        this.setState({fileData: ee.target.result});
      }.bind(this);
    }
    

    您可以找到有关 FileReader here 的更多信息。

    【讨论】:

    • 这就是为什么你不能用文件类型设置输入值的原因。试试render() { if (this.state.fileData) { thumbnail = &lt;img src={this.state.fileData} /&gt; } return thumbnail; } 应该就能看到你的img了。
    猜你喜欢
    • 1970-01-01
    • 2012-07-08
    • 2021-07-31
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多