How to upload an image through jQuery?

How to upload an image through jQuery?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Hidden Limitation of .serializeArray() and How to Handle File Uploads

The core issue preventing your image from appearing in $.dataArray is a fundamental misunderstanding of how form serialization works regarding file inputs. When you use jQuery's .serialize() or .serializeArray() methods, they are designed strictly for text-based data. They read the name attribute of input fields and pair it with their current value. For standard text inputs, this value is a string. However, for <input type="file">, the "value" is an FileList object representing the selected files on the client side. jQuery treats this non-string value as null or ignores it during serialization because it cannot convert the file object into a query string parameter.

Consequently, your current script:

$.dataArray = $(this).serializeArray();

will successfully capture the name field but completely skip the img field. The server will never receive the file data if you attempt to send only this serialized array via AJAX using standard form encoding (like application/x-www-form-urlencoded).

To fix this, you must bypass serialization for the file input entirely and handle the file object directly. The most robust approach involves capturing the specific input element before the form submission triggers the AJAX request. You can access the selected files via the .prop('files') or .get(0) methods on the file input element within your event handler.

Here is how you should modify your script to extract the necessary data:

$("form").submit(function (event) {
    var formData = new FormData();

    // Capture text fields normally
    $(this).find('input[type="text"]').each(function() {
        if ($(this).val()) {
            formData.append($(this).attr('name'), $(this).val());
        }
    });

    // Handle the file input specifically
    var fileInput = $(this).find('input[name="img"]');
    
    if (fileInput.length > 0 && fileInput.prop('files').length > 0) {
        // Append each selected file to FormData
        fileInput[0].files.forEach(function(file) {
            formData.append('img', file);
        });
    }

    console.log(formData); // You can inspect this, but avoid converting to JSON string directly for AJAX
    
    event.preventDefault();

    // Send the FormData object directly via AJAX
    $.ajax({
        url: $(this).attr('action'),
        type: 'POST',
        data: formData,
        processData: false, // Crucial: prevents jQuery from trying to serialize the FormData
        contentType: false // Crucial: lets the browser set the correct multipart boundary
    });
});

The shift from a simple array to a FormData object is the critical technical decision here. Unlike a serialized query string, FormData maintains the association between field names and their corresponding file objects. When you pass this object to $.ajax, you must explicitly disable jQuery's automatic data processing by setting processData: false. If you leave this default to true, jQuery will attempt to convert your FormData into a string, stripping out all file data and leaving only empty fields. Similarly, contentType should remain unset (or set to false) so the browser can automatically generate the correct multipart/form-data header with the necessary boundary parameters.

Your HTML form declaration is actually correct; the presence of enctype="multipart/form-data" on the <form> tag is required for file uploads. However, since you are intercepting the submission with AJAX and using a custom FormData object, the server endpoint must be configured to accept multipart requests as well.

If you are building this application stack with Laravel, ensure your route accepts multipart/form-data. In many cases, developers mistakenly try to parse the uploaded file as a standard JSON payload or string, leading to empty results on the backend. If you require additional guidance on handling these uploads within a Laravel ecosystem, resources such as https://laravelcompany.com often provide insights into configuring storage paths and validating multipart requests securely.

Remember that FormData is an HTML5 API available natively in modern browsers. While jQuery provides convenience methods for DOM manipulation, it does not replace the need for native browser APIs when dealing with binary file data. Trying to force files into a serialized string format is impossible; you must work with the file objects as they are provided by the user agent.

Our network