-
CI框架结合jQuery实现上传多张图片即时显示
一、Html代码如下:
<tr> <td class="txt_r"><span class="orange">* </span>上传图片:</td> <td id="picInput"> <form id="upload_form" method="post" enctype="multipart/form-data" style="" action="/admin/upload/uploadCover" > <input type="file" size="30" name="userfile[]" id="userfile" class="input" onchange="$('#upload_form').submit();return false;" multiple="multiple"> </form> </td> </tr> <tr> <td> </td> <td> <div id="preview_cover" style="display:none;margin-top: 5px;" > </div> </td> </tr>
二、jQuery代码如下:
$(function(){
$('#upload_form').submit(function(){
var val = $("#userfile").val();
if(val === ''){
weebox_popInfo('e','请选择要上传的图片!','','alert');
return false;
}
var filepath =/\.(jpg|jpeg|gif|JPG|JPEG|GIF|PNG|png)$/i;
if(!filepath.test(val)){
weebox_popInfo('e','要求为图片文件!','','alert');
return false;
}
$(this).ajaxSubmit(uploadOptions);
return false;
});
var uploadOptions = {
dataType:'json',
clearForm:true,
resetForm:true,
beforeSubmit: beforeSubmit,
success: function(json) {
var imgStr = "";
var urlString = "";
if(json.code==1){
var imgArr = json.url;
if($.isArray(imgArr)){
urlString = imgArr.join(',');
for(var i=0;i<imgArr.length;i++){
imgStr += "<div id='thumb"+i+"' style='width:100px; height:125px; float:left;margin-right: 10px;'>";
imgStr += "<img src='"+imgArr[i]+"' style='width: 100px;height: 100px;float: left;'/><br/>";
imgStr += "<input type='radio' name='default_picture' id='default_picture' value='"+imgArr[i]+"' style='width: 20px;height: 18px;float:left;' />主图";
imgStr += "<a id='delete' onclick='delete_cover(this)' style='width: 20px;height: 20px;margin-left: 12px;text-decoration: none;color:#ff5a54;'>删除</a>";
imgStr += "</div>";
}
}else{
urlString = imgArr;
imgStr += "<div id='thumb0' style='width:100px; height:125px; float:left;margin-right: 10px;'>";
imgStr += "<img src='"+imgArr+"' style='width: 100px;height: 100px;float: left;'/><br/>";
imgStr += "<input type='radio' name='default_picture' id='default_picture' value='"+imgArr+"' style='width: 20px;height: 18px;float:left;' />主图";
imgStr += "<a id='delete' onclick='delete_cover(this)' style='width: 20px;height: 20px;margin-left: 12px;text-decoration: none;color:#ff5a54;'>删除</a>";
imgStr += "</div>";
}
var existUrl = $("#pictures").val();
var inputTab = "";
if(typeof existUrl !== "undefined"){
var existArr = existUrl.split(',');
for(var j=0;j<imgArr.length;j++){
existArr.push(imgArr[j]);
}
var changeUrl = existArr.join(',');
$("#pictures").val(changeUrl);
}else{
inputTab = "<input type='hidden' name='pictures' id='pictures' value='"+urlString+"'>";
}
imgStr += inputTab;
$('#preview_cover').append(imgStr).show();
}else{
weebox_popInfo('e',json.msg,'','alert');
}
}
};
var beforeSubmit = function() {}
})
function delete_cover(tag) {
if($(tag).prev().attr("checked")){
weebox_popInfo('i', "不能删除主图!");
}else{
$(tag).parent().remove();
}
var checked_img = $(tag).prev().