reactjs - 在 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>
);
}
}
我已经用邮递员测试了这个功能并且它工作得很好,所以这个错误必须在这个代码中。请帮忙
解决方案
看起来错误正在该行中引发:
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
});
}
推荐阅读
- python-3.x - 如何让我的程序识别 item 是字符串还是整数?
- python - f-string 的行为与嵌套格式化的格式化方法不同
- mysql - MySQL Case 语句“调整”
- dart - 在这个例子中如何从互联网上获取数据?
- c# - 发现内存泄漏
- unity3d - Unity5.6.1f 应用在 Android Oreo (8) 上不显示权限对话框
- python-3.x - TemplateDoesNotExist 位于 /music/1/favourite/music/details.html
- c# - C# CollectionAssert.Contains (int[][], int[]) 不通过
- c# - 使用“键”作为规则元素标签
- android - 如果传感器在启动前连接,FTDI 只能打开连接