Last active
May 12, 2021 02:05
-
-
Save yemmyharry/ed10a1b676161c20e6ed4f5e6513a049 to your computer and use it in GitHub Desktop.
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
import React, { useState } from "react"; | |
import axios from "axios"; | |
export default function ImageUploader() { | |
const [postImage, setPostImage] = useState({ | |
myFile: "", | |
}); | |
const url = "http://localhost:5000/uploads"; | |
const createImage = (newImage) => axios.post(url, newImage); | |
const createPost = async (post) => { | |
try { | |
await createImage(post); | |
} catch (error) { | |
console.log(error.message); | |
} | |
}; | |
const handleSubmit = (e) => { | |
e.preventDefault(); | |
createPost(postImage); | |
}; | |
const convertToBase64 = (file) => { | |
return new Promise((resolve, reject) => { | |
const fileReader = new FileReader(); | |
fileReader.readAsDataURL(file); | |
fileReader.onload = () => { | |
resolve(fileReader.result); | |
}; | |
fileReader.onerror = (error) => { | |
reject(error); | |
}; | |
}); | |
}; | |
const handleFileUpload = async (e) => { | |
const file = e.target.files[0]; | |
const base64 = await convertToBase64(file); | |
setPostImage({ ...postImage, myFile: base64 }); | |
}; | |
return ( | |
<div> | |
<form onSubmit={handleSubmit}> | |
<input | |
type="file" | |
label="Image" | |
name="myFile" | |
accept=".jpeg, .png, .jpg" | |
onChange={(e) => handleFileUpload(e)} | |
/> | |
<button>Submit</button> | |
</form> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment