Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add header data in XMLHttpRequest when using formdata?

I'm trying to implement a file upload API, given here :
Mediafire file Upload

I am successfully able to upload the Post data & Get data, but have no clue how to send the x-filename attribute, which is meant to be Header data as given in API guide.

My Code :

xmlhttp=new XMLHttpRequest(); var formData = new FormData();  formData.append("Filedata", document.getElementById("myFile").files[0]);  var photoId = getCookie("user"); // formData.append("x-filename", photoId);            //tried this but doesn't work // xmlhttp.setRequestHeader("x-filename", photoId);   //tried this too (gives error) [edited after diodeous' answer]  xmlhttp.onreadystatechange=function() {     alert("xhr status : "+xmlhttp.readyState); }  var url = "http://www.mediafire.com/api/upload/upload.php?"+"session_token="+getCookie("mSession")+"&action_on_duplicate=keep";  xmlhttp.open("POST", url); // xmlhttp.setRequestHeader("x-filename", photoId);   //tried this too, doesnt work. Infact nothing gets uploaded on mediafire.  [edited after apsillers' answer] // cant get response due to same origin policy xmlhttp.send(formData); 
like image 236
Rajdeep Siddhapura Avatar asked Oct 29 '13 14:10

Rajdeep Siddhapura


People also ask

How do I pass headers in XMLHttpRequest?

setRequestHeader() The XMLHttpRequest method setRequestHeader() sets the value of an HTTP request header. When using setRequestHeader() , you must call it after calling open() , but before calling send() . If this method is called several times with the same header, the values are merged into one single request header.

How do I add multiple headers in XMLHttpRequest?

setRequestHeader sets one header and takes two arguments (the name and the value). If you want to set multiple headers, then call setRequestHeader multiple times. Don't add extra arguments to the first call.

How do I add a header to my HTTP request?

To add custom headers to an HTTP request object, use the AddHeader() method. You can use this method multiple times to add multiple headers. For example: oRequest = RequestBuilder:Build('GET', oURI) :AddHeader('MyCustomHeaderName','MyCustomHeaderValue') :AddHeader('MySecondHeader','MySecondHeaderValue') :Request.


1 Answers

Your error

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):

xmlhttp.open("POST", url); xmlhttp.setRequestHeader("x-filename", photoId); xmlhttp.send(formData); 
like image 146
apsillers Avatar answered Sep 29 '22 00:09

apsillers