HTML代碼
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
<title>原生版實現JS上傳圖片</title>
</head>
<body>
<center><img src="1.jpg" width="200px" height="200px" /></center>
<br/>
<input style="display:none;" onchange="shangchuan();" type="file" id="post_file"/>
<center><button onclick="post_file.click();">上傳圖片</button></center>
<script>
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.update(); }
function shangchuan(){
//var dir = document.getElementById("post_file").value;
var fd = new FormData(); //表單對象
fd.append("1","測試");
fd.append("usefile",document.getElementById("post_file").files[0]);
var ajax = new XMLHttpRequest();
ajax.open("POST","test.php");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
//alert(ajax.responseText);
window.location.reload();
}
}
ajax.send(fd);
}
</script>
</body>
</html>
PHP 代碼
<?phpvar_dump($_POST);
if(file_exists("1.jpg")){
unlink("1.jpg");
}
move_uploaded_file($_FILES["usefile"]["tmp_name"],"1.jpg");
//var_dump($_FILES);
?>