關鍵函數:
/**
* 多圖上傳
* @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']中去。
