MaxPal2
MaxPal2

Reputation: 40

Upload file on server with JS only

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.

Upvotes: 0

Views: 562

Answers (2)

Refat Alsakka
Refat Alsakka

Reputation: 561

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.

Upvotes: 1

PaulS
PaulS

Reputation: 940

JavaScript is Client-Side. You will not be able to upload files to a Server with it. You would need a Server-Side language, such as PHP.

Article on Client vs Server Side

Upvotes: 2

Related Questions