首页 > 解决方案 > 未捕获的类型错误:无法读取未定义的属性“文件”

问题描述

实际上,我正在尝试在服务器上上传文件,为此,我编写了一个handleDocumentChange文件上传功能,当我上传文件然后显示

未捕获的类型错误:无法读取未定义的属性“文件”

这是我的代码:

处理文档更改

handleDocumentChange = (e, name) => {
  let { StudentID } = this.state;
  console.log("STID", StudentID);
  var form = new FormData();
  form.append("document", e.target.files[0]);
  form.append("title", e.target.name);
  http
    .post(`fupload/${StudentID}`, form)
    .then(res => {
      console.log(res);
    })
    .catch(err => {
      console.log(err);
    });
};

输入框

<CardContent className={classes.docName}>
  <Typography variant="body1" component="h2">
    Photograph
    <input
      name="photograph"
      accept="image/png,image/jpeg,image/jpg,application/pdf"
      type="file"
      onChange={e => this.handleDocumentChange("photograph", e)}
      style={{ display: "none" }}
      ref="photograph"
    />
  </Typography>
</CardContent>;

标签: javascriptreactjsfile

解决方案


尝试像这样更改参数顺序,使e作为第一个参数,因为您的函数正在等待e作为第一个参数

<CardContent className={classes.docName}>
                      <Typography variant="body1" component="h2">
                        Photograph
                        <input
                          name="photograph"
                          accept="image/png,image/jpeg,image/jpg,application/pdf"
                          type="file"
                          onChange={e =>
                            this.handleDocumentChange(e,"photograph")
                          }
                          style={{ display: "none" }}
                          ref="photograph"
                        />
                      </Typography>
                    </CardContent>

推荐阅读