import React from 'react'; import Dropzone from 'react-dropzone'; import axios, { AxiosRequestConfig } from 'axios'; import { SoundList, SoundType } from '../../components/SoundList'; import './Soundboard.scss'; let self: any; interface Props { } interface State { percentCompleted: number; password: string; uploaded: boolean; uploadError: string; soundList: SoundType[]; } export class Soundboard extends React.Component { private config: AxiosRequestConfig; private soundListCache: any; constructor() { super(); this.state = { percentCompleted: 0, password: "", uploaded: false, uploadError: " ", soundList: [], }, self = this; } componentDidMount() { this.config = { headers: { 'Content-Type': 'multipart/form-data', }, onUploadProgress: (progressEvent) => { this.setState({ percentCompleted: Math.round( (progressEvent.loaded * 100) / progressEvent.total ), }); } }; this.getSoundList(); } private getSoundList() { if (!this.soundListCache) { axios.get("/api/soundlist").then((response) => { this.soundListCache = response.data; this.setState({ soundList: response.data, }); }).catch((error: any) => { console.error(error.response.data); }); } else { this.setState({ soundList: this.soundListCache, }); } } onDrop(acceptedFiles: any) { if (acceptedFiles.length > 0) { self.uploadFile(acceptedFiles[0]); } } uploadFile(file: any) { let formData = new FormData(); formData.append("name", file.name); formData.append("file", file); formData.append("password", this.state.password); axios.put("/api/upload", formData, this.config) .then(() => { this.setState({ password: "", percentCompleted: 0, uploaded: true, uploadError: " ", }); this.soundListCache = undefined; this.getSoundList(); }).catch((err) => { this.setState({ percentCompleted: 0, uploaded: false, uploadError: err.response.data, }); }); } passwordOnChange(event: any) { this.setState({ password: event.target.value, }); } render() { const { soundList } = this.state; return (
Drop file here to upload.
{this.state.percentCompleted > 0 ?
Uploading: {this.state.percentCompleted}
: ""} {this.state.uploaded ?
File uploded!
: ""}
{this.state.uploadError}
); } }