• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Ajax / Upload files with ajax

Upload files with ajax

Upload files with ajax

This function sends selected files from a fileEle element to a back-end.

const upload = function(fileEle, backendUrl) {
    return new Promise(function(resolve, reject) {
        // Get the list of selected files
        const files = fileEle.files;

        // Create a new FormData
        const formData = new FormData();

        // Loop over the files
        [].forEach.call(files, function(file) {
            formData.append(fileEle.name, file, file.name);
        });

        // Create new Ajax request
        const req = new XMLHttpRequest();
        req.open('POST', backendUrl, true);

        // Handle the events
        req.onload = function() {
            if (req.status >= 200 && req.status < 400) {
                resolve(req.responseText);
            }
        };
        req.onerror = function() {
            reject();
        };

        // Send it
        req.send(formData);
    });
};

Assume that we have a file input that allows user to choose multiple files:

<input type="file" id="upload" multiple />

We can use the following code inside a click event handler of a button which performs the uploading:

const fileEle = document.getElementById('upload');

upload(fileEle, '/path/to/back-end').then(function(response) {
// `response` is what we got from the back-end
// We can parse it if the server returns a JSON
const data = JSON.parse(response);
...
});

Source

https://htmldom.dev/upload-files-with-ajax/

Ajax

Related Snippets:

  • XMLWriter
  • Submit a form with Ajax
  • Ajax Loader 2

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers