Last active
January 19, 2023 09:13
-
-
Save nelsondev19/4d2b9549a3b6929d5cf483d1dc84b2cf to your computer and use it in GitHub Desktop.
How to send multiple files to backend with API Fetch or Axios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>Document</title> | |
| </head> | |
| <body> | |
| <input id="myInput" type="file" multiple /> | |
| <button type="click" id="btn">CLICK</button> | |
| </body> | |
| <script> | |
| //CAPTURAMOS LA IMAGEN SELECCIONADA | |
| const input = document.getElementById("myInput"); | |
| const btn = document.getElementById("btn"); | |
| var filenames = []; | |
| var ficheros = null; | |
| input.addEventListener("change", (e) => { | |
| ficheros = e.target.files; | |
| for (const iterator of e.target.files) { | |
| filenames.push(iterator.filename); | |
| } | |
| }); | |
| btn.addEventListener("click", (e) => { | |
| e.preventDefault(); | |
| // create formData object | |
| const formdata = new FormData(); | |
| filenames.forEach((filename, index) => { | |
| formdata.append("files", ficheros[index], filename); | |
| }); | |
| var requestOptions = { | |
| method: "POST", | |
| body: formdata, | |
| redirect: "follow", | |
| }; | |
| fetch("http://localhost:5000/test", requestOptions) | |
| .then((response) => response.text()) | |
| .then((result) => console.log(result)) | |
| .catch((error) => console.log("error", error)); | |
| }); | |
| </script> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment