Created
October 4, 2018 18:53
-
-
Save elon-gs/ce0f3aa9560f5c9bf43d622a7586acd4 to your computer and use it in GitHub Desktop.
React example component to upload image to Express backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// for backend, see https://gist.github.com/elon-gs/d6adae8b77d7c90cb76b591fef10d24a | |
import React, { Component } from 'react'; | |
import ImageUploader from 'react-images-upload'; | |
import axios from 'axios'; | |
let uploading = false; | |
export default class UploaderComponent extends Component { | |
state = { | |
imagePath: null | |
} | |
handleUpload = (pictures) => { | |
if (!pictures || pictures.length === 0) { | |
this.setState({ imagePath: null }); | |
} else if (!uploading) { | |
uploading = true; | |
// using a variable because setState did not trigger fast enough to avoid redundant function calls | |
const data = new FormData(); | |
data.append('yourFieldHere', 'yourValueHere'); | |
data.append('image', pictures[0]); | |
axios.post(`${API_URL}/upload`, data, { headers: {'Content-Type': 'multipart/form-data' }}).then(({ data }) => { | |
uploading = false; | |
if (data && data.length > 0) { | |
this.setState({ imagePath: data[0] }); | |
} else { | |
console.log('No URL returned'); | |
} | |
}).catch(e => { | |
uploading = false; | |
console.log(e); | |
}); | |
} | |
} | |
render() { | |
return ( | |
<ImageUploader | |
withPreview={true} | |
buttonText='Upload image' | |
onChange={this.handleUpload} | |
imgExtension={['.jpg', '.gif', '.png', '.gif']} | |
maxFileSize={5242880} | |
singleImage={true} | |
/> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment