您的位置:首页 > 编程语言 > PHP开发

php+ajax图片上传,及时文件上传 摆渡整合

2017-02-28 11:35 417 查看
html 

<input type="file" onchange="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,同一页面上传重复图片,上传没有反应。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ajax图片上传 ajax php