求助:php原生态ajax上传图片的问题
<input type="file" id="files" name="files[]" multiple /> <output id="list"></output>
程序代码:
<script> document.getElementById('files').addEventListener('change', UpladFile, false); var image_data; function createRequest() { try { request = new XMLHttpRequest(); } catch (tryMS) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (otherMS) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = null; } } } return request; } function UpladFile(evt) { if(!evt) { evt = window.event; } var files = evt.target.files; for(var i=0,f;f = files[i];i++){ if(!f.type.match('image.*')){ continue; } var reader = new FileReader(); // Closure to capture the file information. reader.onload = (function(theFile) { return function(e) { // Render thumbnail. var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join(''); document.getElementById('list').insertBefore(span, null); image_data = 'image_code=' + e.target.result; }; })(f); var FileController = 'upload.php'; reader.readAsDataURL(f); xhr = createRequest(); if (xhr == null) { alert("Unable to create request"); return; } xhr.onreadystatechange = handleStateChange; xhr.open("POST", FileController, true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(image_data); } } function handleStateChange() { if(xhr.readyState == 4) { if (xhr.status == 200) { alert(xhr.responseText); } } } </script>
程序代码:
<?php if(isset($_POST[image_code])) { echo "success"; } ?>
第一张图片时:
再次选择文件上传:
为什么上传第一张图片的时候php没有读取到POST的数据,之后再次选择文件上传就可以了呢?