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);
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With