thinkphp ajax上传图片处理方法

有一个网站项目用的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
原文地址:https://www.cnblogs.com/stoneryan/p/4223162.html