Skip to content

Javascript FormData append file

  • by

Using the append method of FormData, you can append files into the FormData objects in JavaScript.

Javascript FormData append file

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <div id="app"></div>

  <h1>File Upload & FormData Example</h1>
  <div>
   <input type="file" id="fileInput" />
 </div>

 <script>

   const fileInput = document.querySelector("#fileInput");

   const uploadFile = file => {
    console.log("Uploading file...");
    const API_ENDPOINT = "https://file.io";
    const request = new XMLHttpRequest();
    const formData = new FormData();

    request.open("POST", API_ENDPOINT, true);
    request.onreadystatechange = () => {
      if (request.readyState === 4 && request.status === 200) {
        console.log(request.responseText);
      }
    };
    formData.append("file", file);
    request.send(formData);
  };

  fileInput.addEventListener("change", event => {
    const files = event.target.files;
    uploadFile(files[0]);
  });
</script>

</body>
</html>

Output:

Javascript FormData append file

Source: freecodecamp.org/news/formdata-explained/

Add formdata JavaScript

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"

// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

Do comment if you have any doubts or suggestions on this Js FormData topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *