Thursday, September 4, 2025
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

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6629 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11859 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6717 POSTS0 COMMENTS