React: Uploading Images
Following up on my previous post, I wanted to share how to upload images from your React frontend to your server. It only takes a couple of lines of code, but if everything isn’t lined up, you will be pulling your hair out.
This example was built with Ionic. The form is universal to React frameworks, but rendering the avatar is unique to Ionic
For simplicity’s sake, we are going to build a component that both renders your image and allows for you to upload a new one. Let’s call it Avatar.tsx
First, let’s render an image.
Get Tyler Knapp’s stories in your inbox
Join Medium for free to get updates from this writer.
/components/Avatar.tsx
import React, { useState } from "react";
import { IonText, IonAvatar } from "@ionic/react";
interface AvatarProps {
imageURL: string;
userID: string;
}
const Avatar: React.FC<AvatarProps> = ({ imageURL, userID }) => {
const [url, setURL] = useState<string>("https://images.ctfassets.net/0jkr5d02o14t/4Tsq7upvRUHBdW4HwzeNEy/7f140b351543035dae54015d634c0df4/placeholder.png?h=250");
const placeholder = "https://images.ctfassets.net/0jkr5d02o14t/4Tsq7upvRUHBdW4HwzeNEy/7f140b351543035dae54015d634c0df4/placeholder.png?h=250";
if (imageURL && url === placeholder) {
setURL(imageURL);
}
return (
<div>
<IonAvatar className="avatar">
<img src={`${url}`} alt="avatar" />
</IonAvatar> <IonText>
className="edit-pic"
onClick={}
>
Change Profile Picture
</h5>
</IonText>
</div>
);
};
export default Avatar;
So, I am passing this component some user data from a fetch made in the parent. If the data does not include an imageURL, then it will render a placeholder avatar.
Now to set up the form. We want to conditionally render the input field for the file, so we will create a toggle with some state logic.
/components/Avatar
const [changeProfilePicture, setChangeProfilePicture] = useState<boolean>(
false
);
...
return (
<div>
<IonAvatar className="avatar">
<img src={`${url}`} alt="avatar" />
</IonAvatar>
<form className="image-upload-container">
{changeProfilePicture ? (
<input
name="profilePicture"
type="file"
accept="image/png, image/jpeg"
onChange={(e: any) => {
handleFileUpload(e.target.files ? e.target.files[0] : url);
}}
/>
) : null} <IonText>
<h5
className="edit-pic"
onClick={() => setChangeProfilePicture(!changeProfilePicture)}
>
Change Profile Picture
</h5>
</IonText>
</form>
</div>
);
};
...
Now to create the submit handler. To send a file over HTTP, you need to create a new FormData object then append the file to that object. If you are using fetch, it is best to leave the headers off the POST request so that fetch will generate them for you.
Very important — you must append the file to the FormData with the same key that you use within your server logic. For this example, I used multer singleUpload for an ‘image’, if you do not have these matched up the image will not upload.
const handleFileUpload = async (file: any) => {
const imageData = new FormData();
imageData.append("image", file);
const url = `http://localhost:4000/users/${userID}/add-profile-picture`;
const config = {
method: "POST",
body: imageData,
};
try {
const req = await fetch(url, config);
if (req.ok) {
const res = await req.json();
console.log(res);
if (res.success) {
setURL(res.user.profilePicture);
}
}
} catch (err) {
console.log(err);
}
};








