I'm trying to create a song uploading function using Axios in order to send the data to my server.
The backend requires audio file, image file and name for a single track. So now, if I input an image file, react can recognize that image, but then I input an audio file, It throws me an error:
Uncaught TypeError: Cannot read property '0' of null
Here is my code:
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>
);
}
}
I have tested this feature with postman and It worked fine, so the bug must be in this code. Please help