Skip to content

Instantly share code, notes, and snippets.

@pavinduLakshan
Created June 22, 2020 10:22
Show Gist options
  • Save pavinduLakshan/3c63dfceaf3f9bdead9ffb0283f68bce to your computer and use it in GitHub Desktop.
Save pavinduLakshan/3c63dfceaf3f9bdead9ffb0283f68bce to your computer and use it in GitHub Desktop.
import React, { useState, useRef } from 'react';
import axios from 'axios'
const ImgUpExample = ({mode,btnText,handleSubmit}) => {
const imgUp = useRef(null);
const [image, setImage] = useState();
const [imageName, setImageName] = useState();
function handleImage(e) {
setImage(e.target.files[0]);
setImageName(e.target.files[0].name);
}
function handleFormSubmit(event) {
event.preventDefault();
const data = new FormData();
data.append('file', image);
axios.post('/upload-image', data).then(res => {
if (res.status === 200) {
alert('added');
}
}).catch(err => {
alert('Error occured.');
console.log(err);
})
}
return (
<div>
<form onSubmit={handleFormSubmit}>
<input
type="file"
style={{ display: 'none' }}
ref={imgUp}
onChange={handleImage}
accept="image/*"></input>
<button onClick={e => imgUp.current.click()}>Select photo</button>
<button type="submit">Upload Image</button>
</form>
</div>
);
};
export default ImgUpExample;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment