Saturday, December 28, 2024
Google search engine
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

Recent Comments