要實現異步上傳圖片方法有常用的有二種,一種是利用iframe實現,另一種是借助於ajax來實現一般用第三方插件了。
上傳圖片form提交target到一個隱藏的iframe裡,
代碼如下 復制代碼form action="upload.php" id="form1" name="form1" enctype="multipart/form-data" method="post" target="uploadIframe">
<!--上傳圖片頁面 -->
</form>
<iframe name="uploadIframe" id="uploadIframe" style="display:none"></iframe>
然後後台處理完上傳圖片邏輯後返回給前台,利用ajax修改當前頁面DOM對象實現無刷新上傳圖片的友好功能。
實例
代碼如下 復制代碼a.html
<form enctype="multipart/form-data" action="a.php" target="ifram_sign" method="POST">
<input name="submit" id="submit" value="" type="hidden">
<label>上傳文件: <input name="test_file" type="file" id="test_file" size="48"></label>
<input type="image" value="立即上傳" id="submit_btn">
</form>
<iframe name="ifram_sign" src="" frameborder="0" height="0" width="0" marginheight="0" marginwidth="0"></iframe>
PHP代碼:
代碼如下 復制代碼 <?php其實jquery ajax圖片異步上傳
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US">
<head>
<title>圖片異步上傳</title>
</head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<link type="text/css" rel="stylesheet" href="css/index.css">
<body>
<div class="frm">
<form name="uploadFrom" id="uploadFrom" action="upload.php" method="post" target="tarframe" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upfile">
</form>
<iframe src="" width="0" height="0" style="display:none;" name="tarframe"></iframe>
</div>
<div id="msg">
</div>
</body>
</html>
index.js
$(function(){
$("#upload_file").change(function(){
$("#uploadFrom").submit();
});
});
function stopSend(str){
var im="<img src='upload/images/"+str+"'>";
$("#msg").append(im);
}
upload.php
<?php
$file=$_FILES['upfile'];
$name=rand(0,500000).dechex(rand(0,10000)).".jpg";
move_uploaded_file($file['tmp_name'],"upload/images/".$name);
//調用iframe父窗口的js 函數
echo "<script>parent.stopSend('$name')</script>";
?>