how to upload multiple files as a single file

How to upload single or multiple files the easy way with FormData

In this post, nosotros'll learn about the FormData interface bachelor in modern spider web browsers as a part of the HTML5 spec.

We'll see examples of using FormData with Ajax, Angular 7, Ionic and React.

What's FormData

FormData is simply a data structure that can be used to store key-value pairs. But similar its proper name suggests information technology's designed for holding forms data i.e you can use information technology with JavaScript to build an object that corresponds to an HTML form. It's mostly useful when you need to send course information to RESTful API endpoints, for example to upload single or multiple files using the XMLHttpRequest interface, the fetch() API or Axios.

You can create a FormData object by instantiating the FormData interface using the new operator equally follows:

                const formData = new FormData()                              

The formData reference refers to an instance of FormData. You can call many methods on the object to add and work with pairs of data. Each pair has a fundamental and value.

These are the available methods on FormData objects:

  • append() : used to append a fundamental-value pair to the object. If the key already exists, the value is appended to the original value for that key,
  • delete(): used to  deletes a key-value pair,
  • entries(): returns an Iterator object that you tin can utilize to loop through the listing the central value pairs in the object,
  • go(): used to return the value for a key. If multiple values are appended, it returns the first value,
  • getAll(): used  to return all the values for a specified cardinal,
  • has(): used to check if there'due south a key,
  • keys(): returns an Iterator object which you tin use to list the available keys in the object,
  • set():  used to add together a value to the object, with the specified key. This is going to relace the value if a key already exists,
  • values():  returns an Iterator object for the values of the FormData object.

File Upload Example with Vanilla JavaScript

Let'south now see a elementary case of file upload using vanilla JavaScript, XMLHttpRequest and FormData.

Navigate to your working binder and create and index.html file with the post-obit content:

                <!DOCTYPE html> <html>  <head> 	<championship>Bundle Sandbox</title> 	<meta charset="UTF-8" /> </caput>  <torso> 	<div id="app"></div>  	<script src="index.js"> 	</script> </body>  </html>                              

We simply create an HTML document with a <div> identified past the app ID. Next, we include the index.js file using a <script> tag.

Next, create the index.js file and add together following code:

                document.getElementById("app").innerHTML = ` <h1>File Upload & FormData Example</h1> <div> <input type="file" id="fileInput" /> </div> `;  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.condition === 200) {       console.log(asking.responseText);     }   };   formData.append("file", file);   asking.transport(formData); };  fileInput.addEventListener("change", issue => {   const files = event.target.files;   uploadFile(files[0]); });                              

Nosotros first insert an <input blazon="file" id="fileInput" /> element in our HTML page. This will be used to select the file that we'll be uploading.

Next, we query for  the file input element using the querySelector() method.

Next, nosotros define the uploadFile() method in which nosotros first declare anAPI_ENDPOINT variable that holds the address of our file uploading endpoint. Adjacent, nosotros create an XMLHttpRequest request and an empty FormData object.

We use the append method of FormData to append the file, passed as a parameter to the uploadFile() method, to the file key. This volition create a key-value pair with file equally a key and the content of the passed file equally a value.

Side by side, we ship the request using the send() method of XMLHttpRequest and nosotros pass in the FormData object as an argument.

After defining the uploadFile() method, we listen for the change event on the <input> element and nosotros call theuploadFile() method with the selected file every bit an argument. The file is accessed from outcome.target.files array.

You can experiment with this example from this lawmaking sandbox:

Uploading Multiple Files

Y'all can easily modify the code in a higher place to support multiple file uploading.

Offset, you lot need to add the multiple property to the <input> element:

                <input type="file" id="fileInput" multiple />                              

Now, you'll be able to select multiple files from your drive.

Side by side, change the uploadFile() method to accept an array of files equally an argument and only loop through the array and suspend the files to the FormData object:

                const uploadFile = (files) => {   panel.log("Uploading file...");   const API_ENDPOINT = "https://file.io";   const request = new XMLHttpRequest();   const formData = new FormData();    asking.open("POST", API_ENDPOINT, true);   request.onreadystatechange = () => {     if (request.readyState === four && asking.status === 200) {       console.log(request.responseText);     }   };      for (let i = 0; i < files.length; i++) {     formData.append(files[i].name, files[i])   }   request.transport(formData); };                              

Finally, phone call the method with an assortment of files as argument:

                fileInput.addEventListener("change", outcome => {   const files = event.target.files;   uploadFile(files); });                              

Next, you can check out these advanced tutorials for how to employ FormData with Angular, Ionic and React:

  • How to Post FormData with Angular 7
  • React & Axios FormData
  • Multiple File Upload with Ionic 4 & FormData


Larn to code for costless. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Go started

joneswaallovar.blogspot.com

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

0 Response to "how to upload multiple files as a single file"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel