html
<input type="file" οnchange="ajaxFileUpload(this.files);" />
script
var xhr;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
}
//上传方法
function ajaxFileUpload(file) {
var fileObj = file[0];
var FileController = '../upload.php';
var form = new FormData();
form.append("myfile", fileObj);
createXMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("post", FileController, true);
xhr.send(form);
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
console.log(xhr.responseText);
// json对象转换
var redata = JSON.parse(xhr.responseText);
console.log(redata.filepath);
} else {
alert('fail');
}
}
}
function handleStateChange() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 0) {
var result = xhr.responseText;
var json = eval("(" + result + ")");
alert('图片链接:\n' + json.file);
}
}
}
有个小BUG,同一页面上传重复图片,上传没有反应。