如何在React中使用FileReader? (收到一个奇怪的错误) [英] How to use FileReader with React? (getting a strange error)

查看:718
本文介绍了如何在React中使用FileReader? (收到一个奇怪的错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了

如何在React中使用FileReader?

并遇到与我的代码相同的错误.

and gotten the same error as my code.

我正在尝试在React组件中使用FileReader().

I'm trying to use the FileReader() in a react component.

class Home extends Component {

  onChange(e) {
    let files = e.target.files;
    console.log(files);
    let reader = new FileReader();
    reader.readAsDataURL(files[0]);

    reader.onload = e => {
      console.log(e.target.result);
    };
  }

  render() {
    return (
        <div onSubmit={this.onFormSubmit}>
          <h1>Upload File Here</h1>
          <input type="file" name="file" onChange={e => this.onChange(e)} />
        </div>

export default Home;

console.log(files)返回上传的文件(如果我在没有onChange()代码其余部分的情况下运行它).当我运行整个程序时,我收到一条错误消息:

console.log(files) returns the uploaded file (if I run it without the rest of the onChange() code). When I run the whole thing, I get an error message of:

Error: cannot read as File: {}

我正在严格按照本教程进行操作,对他们来说效果很好.有什么想法吗?!

I'm following this tutorial exactly and it is working fine for them. Any thoughts?!

https://www.youtube.com/watch?v=sp9r6hSWH_o& ; t = 50s

推荐答案

尝试一下

更改

   onChange(e) {
        let files = e.target.files;
         console.log(files);
         let reader = new FileReader();
         reader.readAsDataURL(files[0]);

          reader.onload = e => {
              console.log(e.target.result);
          };
     }

收件人

    onChange = e => {
         let files = e.target.files;
         console.log(files);
         let reader = new FileReader();
         reader.onload = r => {
              console.log(r.target.result);
          };
         reader.readAsDataURL(files[0]);
     }

这篇关于如何在React中使用FileReader? (收到一个奇怪的错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆