Optimize Images up to 80% with AVIF and WEBPSee how it works

How to make image upload with JavaScript

In this article, we will show you how to create an image uploader with JS. You can either write the entire file uploader script or take advantage of the file upload library.

FYI - the latter can make this task safer to use and much easier to create. You can read more about safe uploads and in-browser image editing in our complete guide to implementing file uploading.

To start with the basics – here is a very simple tutorial where you can see how to add file upload functionality to your HTML.

Prerequisites

Now, let's take a deeper look at the file uploader script. It has two functions: one is for the file input element and the other is for the file selection button.

uploadFile

The function for the file input element is pretty simple — it adds the file input element to the page, sets its type to file, and binds the change event to the uploadFile function.

The uploadFile function is called when the user changes the file input element.

File selection button

The function for the file selection button is a bit more complicated. It adds a file selection button, sets its type to image, and adds an onclick event that calls the uploadFiles function.

The uploadFiles function is called when the user clicks on the file selection button.

The uploadFiles function is responsible for binding the file input elements to the form that will be used to send them to the server. It also adds the form element to the page.

After that, it sets up the form action to point to a PHP script on the server and adds the enctype attribute with the value multipart/form-data.

This way, when we send data from the form, it will be sent as a multipart request. Then it sets up a hidden field where we will store our token (this is used to prevent cross-site request forgery attacks).

Finally, it sets up the files property of the form element to an empty array and then iterates through all of the file input elements. For each file input element, it creates a new File object, assigns it to the files property of the form element, and then adds the file input element's name attribute to a hidden field in the form which will be used to identify each file later on.

The file object contains information about each uploaded file, such as its name, its size, its type, and so on. When all of the file input elements have been processed, we make sure that there is at least one file in the files property of the form element before we submit it.

We do this by checking whether or not its length is greater than 0. Finally, we add an event listener for the submit event of the form element which will call the handleUploadSuccess function when the form is submitted successfully.

Handling upload success

This function is called when the form is submitted successfully. Let's take a look at it: First of all, we extract the token from the hidden field where we stored it earlier on in this function.

Then we set up our upload variable with information about this request and assign it to our upload variable. This variable contains information such as the request URL, headers, cookies, etc. We then create a new request object with our upload variable and use it to send our data to our PHP script on the server.

In our PHP script, we check whether or not there were any errors while processing this request. If there were any errors, we return an error message to our users. If there weren't any errors, we extract our token from the request data and save it in our database along with some other information about this request (file names, sizes, etc.).

Finally, we send a success message back to our users and close our PHP script tag.

Handling upload error

This function is called when something goes wrong while uploading our files. Let's take a look at it: First of all, we extract information about this request from our upload variable (request URL, headers, cookies, etc.) and store it in our uploadInfo variable.

Then we create a new response object with our uploadInfo variable and send it back to our users. In our response message, we tell them what went wrong and give them some advice on how they can fix their problem.

We also store information about this request in our log array so that we can keep track of how many times this error has occurred and how many requests were affected by it.

Best libraries for image uploading

Here are most popular Javascript libraries to manage file upload:

jQuery

jQuery File Upload is a free to use plugin for jQuery. It supports drag-and-drop upload, progress bars, validation, preview images and much more. It has an option to receive data as JSON and runs on every browser that supports HTML5.

Uploadcare

Uploadcare is a complete file uploading, processing, and delivery platform that allows you to upload images and videos to the cloud directly through either medium.

import { uploadFile } from "@uploadcare/upload-client";

const data = new Blob(["This is example file"], { type: "text/plain" });
const file = await uploadFile(data, {
    publicKey: "YOUR_PUBLIC_KEY",
    fileName: "example.txt",
});

console.log(file);

Dropzone

Dropzone.js is a powerful file uploader that supports drag and drop and can be easily integrated with any server-side platform. It allows you to upload multiple files at once, to validate file type, size, and more. It is also possible to set up a custom preview for each file type. Dropzone.js is open source and is hosted on GitHub.

FileSaver.js

FileSaver.js is a lightweight library that allows users to upload files via AJAX and then download them after the upload has completed. It is possible to select multiple files and set a custom filename, as well as to set the save path. FileSaver.js is also hosted on GitHub.

FileDrop

FileDrop is a jQuery plugin that allows you to easily upload multiple files at once, with progress bar and drag&drop support. It focuses on browser-based uploads.

How to upload an image to a server

To upload an image to a server, you will need to use the XMLHttpRequest. This is a simple object that can be used to asynchronously load data from the given URL.

You will need to follow the steps below in order to upload an image:

  1. Create the XMLHttpRequest object
  2. Set the desired HTTP request method
  3. Create the response handler function
  4. Send the request by calling the open() method on the XMLHttpRequest object
  5. Process the response by calling the responseXML property of the XMLHttpRequest object
  6. Close the XMLHttpResponse object
  7. Handle any errors that may occur during the process
  8. Check the response status code to determine whether the request was successful or not.

Examples

Simple image upload & display using JS:

<div>
    <input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;">
    <label for="file" style="cursor: pointer;">Upload Image</label>
    <img id="output" width="200" />
</div>

<script>
    var loadFile = function(event) {
        var image = document.getElementById('output');
        image.src = URL.createObjectURL(event.target.files[0]);
    };
</script>

JS Image upload with Uploadcare:

include this into the <head>:

<script>
    UPLOADCARE_PUBLIC_KEY = 'demopublickey';
</script>
<script src="https://ucarecdn.com/libs/widget/3.x/uploadcare.full.min.js"></script>

Now you can use the Uploader:

<input
    type="hidden"
    role="uploadcare-uploader"
    name="my_file_input"
/>

Here’s the entire documentation.

Conclusion

There you have it! A simple image upload with JavaScript.