ajaxFileUpload實現圖片的上傳並預覽
阿新 • • 發佈:2019-01-01
先來個最簡單的 單圖上傳並預覽
html:
<script src="/content/js/jquery-1.10.2.min.js"></script>
<script src="/content/js/ajaxfileupload.js"></script>
引入js檔案
一個顯示圖片的標籤,一個是檔案上傳的input標籤(設定隱藏)<div id="img_upload"> <img id="head" src="/content/images/head.jpg"> <p>頭像</p> <input id="img" name="img" class="hidden" type="file" onchange="up_head()"> </div>
js:
<pre style="font-family: 宋體; font-size: 9.6pt; background-color: rgb(255, 255, 255);"><pre name="code" class="html"> $("#head").click(function(){
$("#img").click();
});
//非同步上傳頭像並預覽 function up_head(){ $.ajaxFileUpload({ url:"index.php?r=admin/uploaduserhead", secureuri: false, fileElementId:"img", dataType: 'text', success:function(data,status){ var res=eval('('+data+')'); $("#head").attr("src",res.url); } }); }
當點選圖片的時候,出發input點選事件,彈出檔案上傳視窗,當檔案上傳後,觸發<span style="font-family: Arial, Helvetica, sans-serif;">up_head()事件,非同步上傳圖片,後臺接收圖片並儲存,返回圖片儲存位置</span>
<span style="font-family:Arial, Helvetica, sans-serif;">把檔案儲存的路徑賦給img標籤的src屬性</span>
後臺PHP:
//非同步上傳使用者頭像 public function actionUploaduserhead(){ $rootPath=dirname(dirname(__FILE__)); $string=explode('.',$_FILES["img"]["name"]); $suffix=$string[count($string)-1]; $filename=time().".".$suffix; $Path=$rootPath."/content/images/userhead/"; move_uploaded_file($_FILES["img"]["tmp_name"],$Path.$filename); $res["url"]="/content/images/userhead/".$filename; echo json_encode($res); }
接收上傳的圖片資訊,並儲存,返回儲存的路徑
見過有一個帖子,用的是html5的方法上傳並預覽,但是理解起來有些困難(恕我資質愚鈍),按著自己的理解寫了一個,下一篇分享一個多圖上傳預覽的
Ps:第一次寫,有不足的地方請多多指正