首页 > 解决方案 > 在 React 中上传多个文件时出错

问题描述

我正在尝试使用 Axios 创建一个歌曲上传功能,以便将数据发送到我的服务器。

后端需要单个音轨的音频文件、图像文件和名称。所以现在,如果我输入一个图像文件,react 可以识别该图像,但是我输入一个音频文件,它会抛出一个错误:

未捕获的类型错误:无法读取 null 的属性“0”

这是我的代码:

export default class Uploader2 extends Component {

  constructor(props) {
    super(props);
    this.state = {
      audio: null,
      image: null,
      name: ""
    };
    this.onFormSubmit = this.onFormSubmit.bind(this);
    this.onChangeHandler = this.onChangeHandler.bind(this);
    this.fileUpload = this.fileUpload.bind(this);
  }

  onFormSubmit(e) {
    e.preventDefault();
    this.fileUpload(this.state.audio, this.state.image, this.state.name).then(
      response => {
        console.log(response.data);
      }
    );
  }

  onChangeHandler(e) {
    this.setState({
      audio: e.target.files[0],
      image: e.target.files[1],
      name: e.target.value
    });
  }

  fileUpload(audio, image, name) {
    const url = "https://xxxx.xx.xxx/api/songs";
    const formData = new FormData();
    formData.append("audio", audio);
    formData.append("image", image);
    formData.append("name", name);
    const config = {
      headers: {
        "content-type": "multipart/form-data",
        Authorization: "Bearer xxxxxxx"
      }
    };
    return axios.post(url, formData, config);
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input
          type="file"
          name="audioUpload"
          onChange={this.onChangeHandler}
          multiple
        />
        <input type="file" name="imageUpload" onChange={this.onChangeHandler} />
        <input type="text" name="name" onChange={this.onChangeHandler} />
        <button type="submit">Upload</button>
      </form>
    );
  }
}

我已经用邮递员测试了这个功能并且它工作得很好,所以这个错误必须在这个代码中。请帮忙

标签: reactjs

解决方案


看起来错误正在该行中引发:

e.target.files[0]

这是因为 e.target.files 可以为空 - 例如,如果您打开选择文件窗口并单击取消。如果没有选择文件,我建议您检查空值而不是 setState:

onChangeHandler(e) {
  if(!e.target.files) {
    return;
  }

    this.setState({
      audio: e.target.files[0],
      image: e.target.files[1],
      name: e.target.value
    });
  }

推荐阅读