Skip to content
Related Articles

Related Articles

How to upload file without form using JavaScript ?

View Discussion
Improve Article
Save Article
  • Last Updated : 12 Jul, 2021

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:


var gfg = new FormData();
// upload.php is the file to be uploaded
    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 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...'POST', form.getAttribute('action'), true);
    // To avoid actual submission of the form
    return false;





Approach 3: This approach is to use simpleUpload plugin.


HTML Code Snippet:



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





JavaScript Snippet:



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








My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!