If you are learning how to build websites and want to let users upload files like images , this guide is for you , Using Axios , a simple JavaScript library , you can send image files to server without reloading the page . In this tutorial we will build a very basic image upload example using plain HTML,JavaScript and Axios.
Uploading an Image Using Axios and AJAX
We will make a simple web page where you can :-
Select an image from your computer , Click a button to upload it , Send this image to a server using Axios without refreshing the page.
This is used when building things like profile picture uploads , contact forms with attachments.
Create a Basic HTML Form.
<input type="file" id="imageInput"> <button onclick="uploadImage()">Upload</button>
This will let you choose an image from your system.
JavaScript to Handle the Upload.
<script> function uploadImage() { const file = document.getElementById('imageInput').files[0]; if (!file) return alert("Pick a file"); const data = new FormData(); data.append('image', file); axios.post('https://example.com/upload', data) .then(() => alert("Uploaded!")) .catch(() => alert("Failed")); } </script>
What happens here :-
- User picks a file.
- We get that file from input.
- Put file in FormData box.
- Send box to server using Axios.
- If it works , we say uploaded.
- If it dosent , we say Failed.
Uploading images using JavaScript can sound scary but with Axios , it becomes very simple. The code is short and clean and easy to understand even if you are just starting with web development .