如何在使用formdata时在XMLHttpRequest中添加标题数据?
我试图实现一个file uploadAPI,在这里给出:
Mediafirefile upload
我成功地能够上载Post数据和获取数据 ,但是不知道如何发送x-filename属性,这个属性是API指南中给出的Header数据 。
我的代码:
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);
你的错误
InvalidStateError:尝试使用不是或不再可用的对象
因为调用open
之后必须调用setRequestHeader
。 只需将您的setRequestHeader
行setRequestHeader
open
行的下方(但在send
之前):
xmlhttp.open("POST", url); xmlhttp.setRequestHeader("x-filename", photoId); xmlhttp.send(formData);
使用: xmlhttp.setRequestHeader(key, value);