Ad

Upload File On Server With JS Only

- 1 answer

I'm looking for a method to Upload a file on my server using Javascript only. I've already tried some method with formData that I found on the forum, but nothing works.

var fileChoose = document.getElementById('file-select');

form.onsubmit =  async function(event) {
event.preventDefault();


// Récupère le fichier sélectionné
var files = fileChoose.files;

// Création d'un objet FormData
var formData = new FormData();
var req = new XMLHttpRequest();
filesConfig = files[0]; // Ajoute le fichier dans une variable

formData.append('fileLoad', filesConfig);

try {
  let r = await fetch('./Files', {method: "POST", body: formData});
  console.log("HTTP response code:",r.status);
  console.log(r);
} catch(e) {
  console.log("Il y'a une erreur...: ", e);
}

This method tells me that the file is successfully sent, but I can't find the file on my server.

Any idea?

Cheers.

Ad

Answer

You have to use Ajax.

How to make Ajax Request

Ajax can call a function from the Server-Side language without loading the page.

So you write the function in your Server-Side language than pass the date via Ajax to the function.

Ad
source: stackoverflow.com
Ad