最簡單的多圖上傳,放大,刪除操作

多圖上傳都遇到過得事情,一開始我還用底層支持多圖的方式,咋咋的。直到看到公司同事寫的多圖上傳,覺得可以借鑑,分享也爲了以後使用。直接代碼
(單圖多圖都支持的)
必須要有1.8.3.min.js 還有需要 必須 layer.js
代碼上

HTML


//多圖上傳 主要是三個 第一個是id priview_sq_img1 for="sq_img1"  對應層級遍歷到什麼html中
//第二個是 srcChanged('author_img', 'sq_img1') author_img 對應數據庫字段 sq_img1對應層級
//第三個是input 裏邊的參數 multiple是否多圖上傳標識 data-maxnum最大上傳數量
<div class="flexL" id="preview_sq_img1">
     <{if $jxsInfo.author_img && $jxsInfo.author_img != ''}>
     <{foreach from=$jxsInfo.author_img key=key item=item}>
     <div class="Uploadimgs flexL">
         <img src="<{$item}>" onclick="picview(this)" class="mr-15"/>
         <i style="background-color: #333;" onclick="removeImg(this, 'author_img')">&#10005;</i>
     </div>
     <{/foreach}>
     <{/if}>
 </div>
 <label for="sq_img1" class="uploadimgcom">
     <input id="" type="file" name="">
     <span>上傳圖片</span>
     <input id="sq_img1" onchange="srcChanged('author_img', 'sq_img1');" data-maxnum="10" type="file" multiple="multiple" style="display: none;">
 </label>
//單圖上傳 同上注意點
<div class="flexL">
        <div class="flexL" id="preview_bb_img">
             <{if $jxsInfo.jxs_banner_img && $jxsInfo.jxs_banner_img != ''}>
             <div class="Uploadimgs flexL">
                 <img src="<{$jxsInfo.jxs_banner_img}>" onclick="picview(this)"  class="mr-15"/>
                 <i style="background-color: #333;" onclick="removeImg(this, 'jxs_banner_img')">&#10005;</i>
             </div>
             <{/if}>
         </div>
         <label for="bb_img" class="uploadimgcom">
             <input id="" type="file" name="">
             <span>banner圖上傳</span>
             <input id="bb_img" onchange="srcChanged('jxs_banner_img', 'bb_img');" type="file" style="display: none;">
         </label>
     </div>
 </div>
//需要有個input 隱藏域 存數據 id都和上邊的對應 
<input type="hidden" id="head_img" name="head_img" value="<{$jxsInfo.head_img}>">
<input type="hidden" id="license_img" name="license_img" value="<{$jxsInfo.license_img}>">
<input type="hidden" id="author_img" name="author_img" value="<{implode(',',$jxsInfo.author_img)}>">

**JQ 有三個 picview放大操作 removeImg多張圖刪除 srcChanged上傳圖片 **

//移除圖片 fileId 移除刪層 父級 和本級 以及對應字段的數據
function removeImg(r, fileId) {
    var picsrc = $(r).prev('img').attr('src');
    var ptObj = $("#" + fileId).val().split(',');
    var idx = $.inArray(picsrc, ptObj);
    if(confirm("確定刪除當前圖片")){
        if (idx != -1) {
            ptObj.splice(idx, 1);
            $("#" + fileId).val(ptObj.join());
            $(r).prev('img').remove();
            $(r).parent().remove();
        } else {
            layer.alert('刪除圖片失敗');
        }
    }
    
}
//圖片放大
function picview(Obj) {
    var img_url = $(Obj).attr('src');  
    var img = new Image();  
    img.src = img_url;
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        area: [img.width + 'px', img.height + 'px'], //寬高
        shadeClose: true,
        content: "<img src=" + img_url + " />"
    });
}
//上傳圖片
function srcChanged(fileId, previewId) {
    var files = $('#' + previewId)[0].files;
    var maxNum = $('#' + previewId).data('maxnum');   //最多上傳5張圖片
    var picnum = $('#preview_' + previewId).children('img').length;
    var fileCount = files.length;
    if (fileCount + picnum >= maxNum + 1) {
        alert("最多隻能上傳"+maxNum+"圖片");
        return false;
    } else {
        var formData = new FormData();
        for (var i = 0; i < fileCount; i++) {
            formData.append("fileupload[]", files[i]);   // 文件對象 ,fileupload必須加中括號   
        }
        //也可以根據fileId 的不同拓展不同的大小 或者寬高 以及 格式(jpg/png/bmp)
        formData.append("thumb", '1');
        formData.append("thumb_width", '60');
        formData.append("thumb_height", '60');
        //需要存放的路徑 開頭 /static/uploads/content/jxs_author/日期-今日/圖片集
        //根據需求自己改
        formData.append("pictype", 'jxs_author');
    }
    layer.load(2);
    $.ajax({
    	//php代碼在下
        url: '/uploadFile/upImage/',
        type: 'POST',
        cache: false,
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json'
    }).done(function (res) {
        layer.closeAll('loading');
        if (res.resultId == 0) {
            var picurl = res.Data;
            //多圖處理
            if ($("#" + previewId).prop('multiple')) {
                var html = '';
                var valObj = [];
                if ($("#" + fileId).val() !== '') {
                    valObj = $("#" + fileId).val().split(",");
                }
                $.each(picurl, function (key, val) {
                    html += ' <div class="Uploadimgs flexL"><img src="' + val + '" onclick="picview(this)" class="mr-15"/>';
                    html += " <i style=\"background-color: #333;\" onclick=\"removeImg(this,'" + fileId + "')\">&#10005;</i></div>";
                    valObj.push(val);
                });
                $('#preview_' + previewId).append(html);
                $("#" + fileId).val(valObj.join());
            } else {
           		//單圖操作
                var html = '';
                html += ' <div class="Uploadimgs flexL"><img src="' + picurl[0] + '" onclick="picview(this)" class="mr-15"/>';
                html += " <i style=\"background-color: #333;\" onclick=\"removeImg(this,'" + fileId + "')\">&#10005;</i></div>";
                $('#preview_' + previewId).html(html);
                $("#" + fileId).val(picurl[0]);
            }


        } else {
            layer.alert(res.Data);
        }
    }).fail(function (res) {
        layer.closeAll('loading');
        layer.alert('出錯了!');
    });
}

PHP
我整理一下 只是針對這次 多圖單圖上傳

private $upconfig = [
		
	'allowSuffix'=> ["jpg","jpeg", "png", "pjpeg","gif","bmp","x-png","csv",'xlsx','xls','pdf'],
	
	'rootPath'=> "./static/uploads/",
	
	'savePath'=> "content/",
	
	'maxSize'=> 2097152, //2M 2 * 1024 * 1024;
	
	'maxHeight'=> 300,
	
	'maxWidth'=>450
];

public function upImageAction(){
	if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
		$photoimg = $_FILES['photoimg'];
		$photoimg1 = $_FILES['photoimg1'];
		$import_data = $_FILES['import_data'];

		$className = "preview";
		if ((isset($photoimg['name']) && !empty($photoimg['name']))) {
			$className = "preview";
		} else {
			$photoimg = $photoimg1;
			$className = "preview1";
		}
		//jq代碼中的 jxs_author
		if(isset($_POST['pictype']) && !empty($_POST['pictype'])){
			$this->upconfig['savePath'] = 'content/'.$_POST['pictype'].'/';
		}
		//上方 $this->upconfig
		$up_ins = Comm_Uploadimg::getInstance($this->upconfig);
		$res = $up_ins->uploadFile();
		
		if($res){
			if(in_array($action,$no_compress_action)){
				//$info =  substr($this->upconfig['rootPath'], 1) . $res['savepath'] . $res['savename'];
				//echo '<img style="padding-right: 5px;" src="' . $info . '"  class="' . $className . '">';
				//exit;
				$img_ins = Comm_Image::getInstance();
				foreach($res as $file){
					$imgpath =  $this->upconfig['rootPath'] . $file['savepath'] . $file['savename'];
					if(in_array($file['ext'],$img_ins->compress_type)){
						$img_ins->open($imgpath)->compress(950,650)->save($imgpath);//壓縮處理;
					}
					$info[] = substr($imgpath, 1);
				}
				$response = Comm_Tools::returnMsg(0,$info,1);
			}
		}else{
			$response = Comm_Tools::returnMsg(1,$up_ins->getError(),1);
		}
		exit($response);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章