thinkphp ajax上傳圖片處理方法

有一個網站項目用的thinkphp框架,不喜歡thinkphp的跳轉提示,想改爲全站ajax提交。php

他碰到一個問題,就是用ajax提交的方式上傳圖片是沒法上傳成功的。html

因爲時間關係,我就直接參與進去,查了下thinkphp的資料,看了這哥們用iframe實現了:http://borissun.iteye.com/blog/1151350ajax

但直接粘貼代碼後發現問題多多,無法實現上傳。同時也看到官方:http://www.thinkphp.cn/code/245.html也不少人說沒法上傳。thinkphp

我想估計是粘貼的時候少了什麼代碼之類的,或修改以後出問題了,但這個思路是很正確的。因而我就在這代碼的基礎上,繼續修改爲網站項目須要的。數據庫

如下貼出代碼,可實現ThinkPHP的ajax的上傳圖片操做,但這些代碼基於上傳功能的測試作的,不少地方,包括樣式、安全過濾等方面還沒考慮周全,若是要用,你們須要自行修改。php框架

第一步:安全

在模板頁<body>處添加以下代碼:框架

<form id="formImg" action="__URL__/ajaximg" method="post" target="hidden_frame" enctype="multipart/form-data">
 <div>
 <input type="hidden" name="sh_id" id="sh_id" value="{$id}">
<!--這裏的{$id}你們能夠隨便填1個進去-->
 <input id="AidImg" type="file" name="AidImg" onchange="uploadImg()"/>
 <div style="display:none;" id="imgError">圖片不可爲空</div>
 <iframe style="display:none" name='hidden_frame' id="hidden_frame"></iframe>
 <div><img id="p_img" src="" width="80" height="80"/> </div>

 <span class="help_inline">尺寸:80*80</span>

 </div>
 </form>

 

模板頁裏的JS代碼:編輯器

function uploadImg() 
 {var names=$("#AidImg").val().split("."); 
 if(names[1]!="gif"&&names[1]!="GIF"&&names[1]!="jpg"&&names[1]!="JPG"&&names[1]!="png"&&names[1]!="PNG") 
 {$("#imgError").html("<span>"+"圖片必須爲gif,jpg,png格式"+"</span>");
 $("#formImg .help-inline").hide(); 
 $("#imgError").show(); 
 return; 
 }
 $("#formImg").submit();
 $("#imgError").show();
 $("#imgError").html("圖片上傳中ing"); 
 } 
 function callback(message,success,lujing) 
 { 
 if(success==false) 
 { 
 $("#imgError").html("<span>"+message+"</span>"); 
 $("#imgError").show(); 
 } 
 else{ 
 $("#imgError").hide(); 
 $(".fromtrs").show();
 $("#formImg .help-inline").hide(); 
 var paths=lujing; 
 $("#p_img").attr("src",lujing+message); 
 $("#p_img").attr("imgname",message); //這裏因爲數據庫裏只存入圖片名稱加後綴名,故和路徑拆開了
 } 
 }

 

PHP裏的代碼:ide

public function ajaximg(){
 $cpimg_n=$_POST['cpimg_n'];
 if($_FILES["AidImg"]["size"]){
 //若是有上傳動做
 if($_FILES["AidImg"]["size"]!=0) {
 $uploadPath = "./Tpl/Public/Uploads/".$sh_id."/product/";
 if ($_FILES["AidImg"]["size"] < 1024 * 1024 * 2){ 
 if ($_FILES["AidImg"]["error"] > 0) {echo "<script>parent.callback('發生未知錯誤上傳失敗,請從新上傳',false)</script>";} 
 else {$suffix = substr($_FILES["AidImg"]["name"], strrpos($_FILES["AidImg"]["name"], '.') + 1);
 if($cpimg_n){//若是是修改產品 --這個地方你們不用理會- -根據本身須要修改
 $cpimg_n = substr($cpimg_n, 0,strrpos($cpimg_n, '.'))."g"; 
 $name = $cpimg_n."." .$suffix;
 }
 else{
 //若是是添加產品
 $cpid=100000; //這個根據本身須要請修改
 $name = $sh_id ."_".$cpid. "." .$suffix;
 }
 if (!is_dir($uploadPath)) {
 //沒有目錄建立目錄
 if(mkdir($uploadPath,0777)){echo("<script>parent.callback('正在爲圖片建立目錄',false)</script>");}else{echo("<script>parent.callback('沒法建立該商戶圖片目錄,請聯繫網站管理員',false)</script>");exit;}
 } 
 if (move_uploaded_file($_FILES["AidImg"]["tmp_name"], $uploadPath . "/" . $name)) {
 //若是已經移動成功了
 $lujingg="/Tpl/Public/Uploads/".$sh_id."/product/";//傳過去的路徑
 $imgname=$name;//傳過去的圖片名入庫用
 echo "<script>parent.callback('".$imgname."',true,'".$lujingg."')</script>"; exit;
 } 

 }
 }//end if ($_FILES["AidImg"]["size"] < 1024 * 1024 * 2)
 else {echo "<script>parent.callback('圖片大小不能超過2M',false)</script>";return;} 
 }//end if($_FILES["AidImg"]["size"]!=0)
 else{echo "<script>parent.callback('無此路徑',false)</script>";exit;}
 } //end if($_FILES["AidImg"]["size"])
 else{echo "<script>parent.callback('請上傳圖片',false)</script>"; }
}//end public function ajaximg()

 

以上是單純ajax上傳圖片的方法,已測試OK。

實際使用過程當中,可能頁面中還有其餘的input要結合一塊兒提交。這時候須要分爲2步驟完成,

第一步是點擊上傳圖片(這時候尚未數據庫操做,僅僅是生成圖片。也就是上面說的ajax上傳圖片操做);

第二步,將圖片名稱和其餘的input值一塊兒傳過去入庫操做便可。

順便貼一個ajax提交的例子:

function ajax_form()
 { var id=$("#id").val();
 var p_title=$("#p_title").val();
 var p_img=$("#p_img").attr("imgname");
 var p_summary=$("#p_summary").val();
 var sh_id=$("#sh_id").val();
 var login_user_id=$("#login_user_id").val();
 var baocun=$("input[type=submit]").attr("baocun");
 if(baocun=='1'){alert("已添加成功,請勿重複操做");
 window.location="__URL__/sjcp/id/"+login_user_id;
 }
 var p_summary= $(document.getElementsByTagName('iframe')[1].contentWindow.document.body).html();//這玩意是編輯器,這裏是第二個iframe,第一個就是上傳圖片那個iframe
 var url="__URL__/XXXXXXXX";
$.ajax({
 type: "POST",
 timeout: 10000, 
 url: url,
 data:{id:id,p_title:p_title,p_img:p_img,p_summary:p_summary,sh_id:sh_id},
 cache:false,
 beforeSend: function(){
 $('[tishi=true]').html("保存中");
 },
 error: function(){
 $('[tishi=true]').html("保存失敗");
 },
 success: function(data){
 $('[tishi=true]').html(data);
 $("input[type=submit]").attr("baocun","1");
 }
 });
 }源文件地址:  http://www.caijierui.com/blog/?p=79
相關文章
相關標籤/搜索