How to Upload a File with the Click of an Image with jQuery



JQuery


In this article, we show how to upload a file with the click of an image with jQuery.

Many websites have this. Websites such as facebook, youtube, and many others implement this.

Facebook has a 'Upload Photo' image for photo uploads. Youtube has a 'Select files to upload' image. When these images are clicked, a user can select the file that sh/he wants to upload.

So how can this be implemented in code?

This is what we'll do.

We of course need a input tag of type, "file". We then give this input tag an id, so that we can identify it on the page.

We then have our image that when clicked will click the file input tag.

We set up jQuery code so that when the image is clicked, we click the file input tag.

So let's get into this code.



We have to allow for jQuery, so we use the google CDN to allow for jQuery.

We then write a script so that when the HTML element with an id of 'picture' gets clicked, we click the HTML element with an id of 'fileinput'.

We then have our form. Because the form allows for a file upload, you must include, enctype="multipart/form-data"

We then have an image in this form that has an id of "picture". This is the image that when clicked will allow for us to select a file.

Right below this form, we add a file input. This allows for a user to select a file. This file has an id of "fileinput".

Below this, we then have a submit button.

So, again, we have our image and then a file select right below this image.

We write jQuery so that when the image is clicked, the file input element gets clicked.

To show you how this works, see the image below.

Upload photo image

And this is all that is required to upload a file with a click of an image with jQuery.


Related Resources

How to Create a Comment System in Which Only One Reply Comment Box Can Be Open At Once with jQuery



HTML Comment Box is loading comments...