Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest to upload a file with parameters

Tags:

javascript

I want to upload a file using XMLHTTRequest for Safari 5.1 and pass parameters in the POST request.How can this be achieved?It should be in plain javascript without using any API and I am doing this as Safari does not support FileReader in 5.1 version.

var fd = new FormData();
fd.append('file', $files[i]);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function(){alert("Done!");}, false);
xhr.open("POST", url.getUrl('myurl'));
xhr.send(fd);

Is the above piece of code correct?How do I pass parameters to the POST request.

like image 924
GGGG Avatar asked Nov 21 '22 22:11

GGGG


1 Answers

The code looks good. If you want to pass additional parameters to the POST you will have to add them to the FormData.

var fd = new FormData();
// here the POST parameters
fd.append('parameter1', 'XXXX' );
fd.append('parameter2', 'YYYY' );
// The rest of your code
fd.append('file', $files[i]);
...

EDIT: I am not sure however if this functionality is supported in Safari 5.1

like image 72
Danilo Tommasina Avatar answered Dec 01 '22 18:12

Danilo Tommasina