有一個網站項目用的thinkphp框架,不喜歡thinkphp的跳轉提示,想改成全站ajax提交。
他碰到一個問題,就是用ajax提交的方式上傳圖片是無法上傳成功的。
由於時間關系,我就直接參與進去,查了下thinkphp的資料,看了這哥們用iframe實現了:http://borissun.iteye.com/blog/1151350
但直接粘貼代碼后發現問題多多,沒法實現上傳。同時也看到官方:http://www.thinkphp.cn/code/245.html也很多人說無法上傳。
我想估計是粘貼的時候少了什么代碼之類的,或修改之后出問題了,但這個思路是很正確的。於是我就在這代碼的基礎上,繼續修改成網站項目需要的。
以下貼出代碼,可實現ThinkPHP的ajax的上傳圖片操作,但這些代碼基於上傳功能的測試做的,很多地方,包括樣式、安全過濾等方面還沒考慮周全,如果要用,大家需要自行修改。
第一步:
在模板頁<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里的代碼:
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