ThinkCMF-上传多个图片源码解读
关键函数:
/** * 多图上传 * @param dialog_title 上传对话框标题 * @param container_selector 图片容器 * @param item_tpl_wrapper_id 单个图片html模板容器id * @param extra_params 额外参数,object * @param app 应用名,CMF 的应用名 */ function upload_multi_image(dialog_title, container_selector, item_tpl_wrapper_id, extra_params, app) { open_upload_dialog(dialog_title, function (dialog, files) { var tpl = $('#' + item_tpl_wrapper_id).html(); var html = ''; $.each(files, function (i, item) { var itemtpl = tpl; itemtpl = itemtpl.replace(/\{id\}/g, item.id); itemtpl = itemtpl.replace(/\{url\}/g, item.url); itemtpl = itemtpl.replace(/\{preview_url\}/g, item.preview_url); itemtpl = itemtpl.replace(/\{filepath\}/g, item.filepath); itemtpl = itemtpl.replace(/\{name\}/g, item.name); html += itemtpl; }); $(container_selector).append(html); }, extra_params, 1, 'image', app); }
使用案例:
1. 关键元素:
<tr> <th>相册图集</th> <td> <ul id="photos" class="pic-list unstyled"></ul> <a href="javascript:upload_multi_image('图片上传','#photos','photos-item-wrapper');" class="btn btn-small">选择图片</a> </td> </tr>
2. 关键模板:
<script type="text/html" id="photos-item-wrapper"> <li id="savedimage{id}"> <input id="photo-{id}" type="hidden" name="photos_url[]" value="{filepath}"> <input id="photo-{id}-name" type="text" name="photos_alt[]" value="{name}" style="width: 160px;" title="图片名称"> <img id="photo-{id}-preview" src="{url}" style="height:36px;width: 36px;" onclick="parent.image_preview_dialog(this.src);"> <a href="javascript:upload_one_image('图片上传','#photo-{id}');">替换</a> <a href="javascript:(function(){$('#savedimage{id}').remove();})();">移除</a> </li> </script>
3. 关键后台代码:
// 文章添加提交 public function add_post(){ if (IS_POST) { if(empty($_POST['term'])){ $this->error("请至少选择一个分类!"); } if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){ foreach ($_POST['photos_url'] as $key=>$url){ $photourl=sp_asset_relative_url($url); $_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]); } } $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']); $_POST['post']['post_modified']=date("Y-m-d H:i:s",time()); $_POST['post']['post_author']=get_current_admin_id(); $article=I("post.post"); $article['smeta']=json_encode($_POST['smeta']); $article['post_content']=htmlspecialchars_decode($article['post_content']); $result=$this->posts_model->add($article); if ($result) { foreach ($_POST['term'] as $mterm_id){ $this->term_relationships_model->add(array("term_id"=>intval($mterm_id),"object_id"=>$result)); } $this->success("添加成功!"); } else { $this->error("添加失败!"); } } }
如果存在上传多个文件的情况存在,即判断是否存在photos_alt和photos_url,如果存在则将多个上传图片存放到smeta['photo']中去。