Saturday, February 7, 2026
HomeLanguagesJavascriptHow to upload file without form using JavaScript ?

How to upload file without form using JavaScript ?

There are several approaches to upload a file without using the form in JavaScript:

Approach 1: This approach is to use FormData that can upload a file without using any kind of form. The special thing about this is that network methods, such as fetch, can accept a FormData object as a body. It’s encoded and sent out with Content-Type — multipart/form-data.

JavaScript Snippet:

Javascript




var gfg = new FormData();
 
gfg.append('pictureFile',
        pictureInput.files[0]);
 
// upload.php is the file to be uploaded
$.ajax({
    url: 'upload.php',
    type: 'POST',
    processData: false,
    contentType: false,
    dataType: 'json',
    data: gfg
});


 

 

 

 

Approach 2: This approach is to use XMLHTTPRequest that can directly upload the file as the content inside the body of POST request.

 

JavaScript Snippet:

 

Javascript




// JavaScript Code
var form = document.getElementById('the-form');
 
form.onsubmit = function () {
    var formData = new FormData(form);
    formData.append('file', file);
    var xhr = new XMLHttpRequest();
 
    // Add any event handlers here...
    xhr.open('POST', form.getAttribute('action'), true);
    xhr.send(formData);
 
    // To avoid actual submission of the form
    return false;
}


 

 

 

 

Approach 3: This approach is to use simpleUpload plugin.

 

HTML Code Snippet:

 

HTML




<!DOCTYPE html>
<html>
 
<body>
    <h2>Welcome To GFG</h2>
 
    <input type="file" name="arquivo"
        id="simpleUpload" multiple>
     
        <button type="button" id="upload">
            Upload
        </button>
</body>
 
</html>


 

 

 

 

JavaScript Snippet:

 

Javascript




$('#simpleUpload').simpleUpload({
 
    // upload.php is the file
    // to be uploaded
    url: 'upload.php',
    trigger: '#upload',
    success: function (data) {
        alert('Successfully Uploaded');
    }
});


 

 

 

 

Output:

 

 

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32493 POSTS0 COMMENTS
Milvus
126 POSTS0 COMMENTS
Nango Kala
6864 POSTS0 COMMENTS
Nicole Veronica
11990 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12083 POSTS0 COMMENTS
Shaida Kate Naidoo
7000 POSTS0 COMMENTS
Ted Musemwa
7241 POSTS0 COMMENTS
Thapelo Manthata
6951 POSTS0 COMMENTS
Umr Jansen
6936 POSTS0 COMMENTS