Uploading Multiple Images without a Library
Answered
Baldfaced hornet posted this in #help-forum
Baldfaced hornetOP
So I have a form where users can submit 1 or more pictures to add to a listing. This form ends up being submitted to a backend Java application that will store the necessary information in a DB table/blob.
The question here is how to properly handle multiple image uploads?
I have a bit of starting code and a rough idea of where to go from here but am curious if there is a better alternative or in getting a little assistance over some obstacles.
The question here is how to properly handle multiple image uploads?
I have a bit of starting code and a rough idea of where to go from here but am curious if there is a better alternative or in getting a little assistance over some obstacles.
const handleChangeImage = (e: ChangeEvent<HTMLInputElement>) => {
e.preventDefault();
const file = e.target.files?.[0];
if (!file) return;
if (!file.type.includes('image')) {
return alert('Please upload an image file');
}
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const result = reader.result as string;
handleStateChange('image', result);
}
};const handleStateChange = (fieldName: string, value: string) => {
setform((prevState) =>
({ ...prevState, [fieldName]: value}))
};const [form, setform] = useState({
title: '',
image: '',
details: '',
price: '',
quantity: ''
})<div className="flexStart form_image-container">
<label htmlFor="listing" className="flexCenter form_image-label">
{!form.image && 'Please add some pictures to your listing'}
</label>
<input
id="image"
type="file"
accept="image/*"
required={type === 'create'}
className="form_image-input"
multiple
onChange={handleChangeImage}
/>
{form.image && (
<Image
src={form?.image!}
className="sm:p-10 object-contain z-20"
alt="Listing image"
fill
/>
)}
</div>4 Replies
Baldfaced hornetOP
This results in a page like so where I can choose to upload 1 image and it will be shown.
I imagine the difference I need is to somehow change it where this input field instead adds image files to a list/array with a counter attached to them.
Then the array will be looped over to re-display the pictures to the user uploading and the value(number) so they can be removed if they choose to.
I imagine the difference I need is to somehow change it where this input field instead adds image files to a list/array with a counter attached to them.
Then the array will be looped over to re-display the pictures to the user uploading and the value(number) so they can be removed if they choose to.
Baldfaced hornetOP
Answer
Baldfaced hornetOP
^This is by far the best video you will find on how to do this without using some external library that will charge you out the rear end to scale.
Just take the main concept from the video and adjust it as needed for your own project.