Clément Andraud
Clément Andraud

Reputation: 9279

Upload file with ajax and formData

I'm trying to upload a video to the Dailymotion API with ajax.

In my script i have :

                //upload the video and get the url
                var xhr =  new XMLHttpRequest();
                xhr.open('POST', upload_url, true);
                var formData = new FormData(document.getElementById("myForm"));
                xhr.send(formData);

My script is working but i have a problem, how can I specify which file field i want to use ?

If you see var formData = new FormData(document.getElementById("myForm"));, myForm is the entire form, if my file input has id="myInput", how can i specify that ?

I don't want to send all my form, but just one specific field.

Thanks !

Upvotes: 0

Views: 497

Answers (2)

Clément Andraud
Clément Andraud

Reputation: 9279

This do what i want :

var file = document.getElementById("myInput").files[0];
var formData = new FormData();
formData.append('file', file);

Upvotes: 1

CoqPwner
CoqPwner

Reputation: 964

Create en empty FormData and add the file value to it manually:

var file = document.getElementById("myInput").value;
var formData = new FormData();
formData.append('file', file);

Upvotes: 0

Related Questions