import { endpoint } from '../config' const FileFields = props => (
) const FileState = { file: null, name: '', description: '', filename: '', mimetype: '', size: '', path: '', uploading: false } async function uploadFile(file) { const body = new FormData() body.append('file', file) const res = await fetch(`${endpoint}/upload`, { method: 'POST', body }) return res.json() } class FileUpload extends React.Component { state = { ...FileState } upload = async event => { event.preventDefault() if (!this.state.file) { alert('Please select file first.') return } this.setState({ uploading: true }) const data = new FormData() data.append('file', this.state.file) data.append('description', this.state.description) const res = await fetch(`${endpoint}/upload`, { method: 'POST', body: data }) const { error, file } = await res.json() if (error) { console.error(error) alert('Upload error.') this.setState({ uploading: false }) } this.setState({ path: `${endpoint}/${file.path}`, uploading: false }) } selectFile = event => { const { validity, files } = event.target this.setState({ file: files[0] }) } handleChange = event => { this.setState({ [event.target.name]: event.target.value }) } render() { return ( ) } } export default FileUpload export { FileFields, FileState, uploadFile }