ajaxFileUpload ajax 文件上传 php
<script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> <script src="https://files.cnblogs.com/files/yutaoyao/ajaxFileUpload.js"></script> <script type="text/javascript"> function ajaxFileUpload(id) { //加载图标 /* $("#loading").ajaxStart(function(){ $(this).show(); }).ajaxComplete(function(){ $(this).hide(); });*/ $.ajaxFileUpload({ url: "{:U('User/upload_file')}", secureuri :false, fileElementId :'url_img', dataType : 'json', success : function (data, status){ var data=JSON.parse(data); if(data.retcode==1){ $("#url_img_pre").attr("src",'http://{$_SERVER['HTTP_HOST']}/'+data.thumbsrc); $("#img_thumb").val(data.thumbsrc); $("#img").val(data.filesrc); }else{ alert(data.msg+"code:"+data.retcode) } }, error: function(data, status, e){ alert(e); } }) return false; } </script>
<form onsubmit="return false" enctype="multipart/form-data"> <input type="file" id="url_img" name="url_img" onchange="return ajaxFileUpload(this.id)" /> <input type="hidden" id="img" name="img" value="{$url.img}"/> <input type="hidden" id="img_thumb" name="img_thumb" value="{$url.img_thumb}"/> <img src="{$url.img_thumb|url_right}" id="url_img_pre" /> </form> <button type="button" id="eidt_submit">提交</button>
if ($_FILES) { $filepath = 'Public/Uploads/user/' . getcookies ( 'uid' ) . '/'; // 设置附件上传目录 $thumbPath = 'Public/Uploads/user/' . getcookies ( 'uid' ) . '/thumb/'; // 设置缩略图上传目录 if (! (create_folders ( $filepath )) or ! (create_folders ( $thumbPath ))) { $res ["msg"] = "文件夹创建失败,请联系管理员"; } else { $info = UploadFiles2 ( $filepath, 100, 100, $thumbPath ); if ($info ['err'] == 1) { $res ["retcode"] = 2; $res ["msg"] = $info ['msg']; } elseif (! isset ( $info ['err'] )) { $res ["retcode"] = 1; $res ["msg"] = "yes"; for($i = 0; $i < count ( $info ); $i ++) { $filesrc [$i] = $filepath . $info [$i] ['savename']; $thumbsrc [$i] = $thumbPath . 'thumb_' . $info [$i] ['savename']; } $res ["filesrc"] = $filesrc; $res ["thumbsrc"] = $thumbsrc; } } echo json_encode ( $res ); }
function UploadFiles2($path,$thumbwidth,$thumbheight,$thumbPath){ //文件上传公用函数(需要缩略图) import("ORG.Net.UploadFile"); $upload = new UploadFile(); // 实例化上传类 $upload->maxSize = C('file_uplode_maxSize') ; // 设置附件上传大小 $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg') ; // 设置附件上传类型 array('jpg', 'gif', 'png', 'jpeg') $upload->savePath = $path ;// 设置附件上传目录 './Public/Uploads/' $upload->saveRule = time().'_'.mt_rand(10,99); $upload->thumb = true; $upload->thumbMaxWidth =$thumbwidth; $upload->thumbPath=$thumbPath; $upload->thumbMaxHeight =$thumbheight; if(!$upload->upload()) { // 上传错误提示错误信息 return array('err'=>1,'msg'=>$upload->getErrorMsg()); }else{ // 上传成功 获取上传文件信息 return $upload->getUploadFileInfo(); } }