Skip to content

Instantly share code, notes, and snippets.

@yemmyharry
Last active May 12, 2021 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yemmyharry/ed10a1b676161c20e6ed4f5e6513a049 to your computer and use it in GitHub Desktop.
Save yemmyharry/ed10a1b676161c20e6ed4f5e6513a049 to your computer and use it in GitHub Desktop.
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