Related Articles

Related Articles

How to upload file without form using JavaScript ?
  • Last Updated : 05 Nov, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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
});

chevron_right




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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
}

chevron_right


Approach 3: This approach is to use simpleUpload plugin.

HTML Code Snippet:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


JavaScript Snippet:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :