So I'm not sure why this piece of code isn't working. What I have is an array of file types the component accepts. I try to iterate over the that array and check if the file being uploaded is of one of those types. If it is NOT then I return;
. For some reason the code below acceptedFormats.forEach
continues to run. If I console.log
the audioType
and file.type
I get an INVALID
for each. So again shouldn't it be returning? Thanks!
class Upload extends React.Component {
state = {
percentage: 0,
uploading: false
}
handleUpload = (e) => {
if (this.state.uploading) {
return;
}
const file = e.target.files[0];
const acceptedFormats = ["audio/wav", "audio/mp3", "audio/m4a"];
// TODO: Figure out why this isn't working
acceptedFormats.forEach((audioType) => {
console.log(audioType);
console.log(file.type);
if(audioType !== file.type) {
console.log('INVALID');
return;
}
})
const audioRef = storageRef.child('audio/' + file.name);
const task = audioRef.put(file);
task.on('state_changed', function(snapshot){
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
this.setState(() => ({
percentage: progress
}))
}.bind(this), function(error) {
}, function() {
const downloadURL = task.snapshot.downloadURL;
const fileName = task.snapshot.metadata.name;
let songName = removeFileExtension(file.name);
songName.replace(/\./g,' ');
db.ref(`users/${this.props.uid}/uploadedSongs/`).push({
downloadURL,
fileName,
songName,
}).then(() => {
this.setState({
percentage: 0,
uploading: false
})
Alert.success(`Upload successful`, {
position: 'top-right',
effect: 'slide',
timeout: 3000
})
})
}.bind(this));
}
render() {
return (
<div className="Upload">
<label className={this.state.uploading ? "Upload__button-disabled btn" : "Upload__button btn"}>
<span className="Upload__button-text">{this.state.uploading ? "Uploading" : "Upload a song"}</span>
<input className="Upload__input" type="file" onChange={(e) => this.handleUpload(e)} disabled={this.state.uploading ? true : false}/>
</label>
<span style={{color: '#808080', fontSize: '12px'}}>Accepted formats: .wav, .mp3, .m4a</span>
</div>
);
}
}
ReactDOM.render(<Upload />, document.querySelector('#u'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.0/react-dom.min.js"></script>
<h1>Example Upload</h1>
<div id="u"></div>