[jQuery] 쇼핑몰 대표 이미지 상품박스[jQuery] 쇼핑몰 대표 이미지 상품박스

Posted at 2018. 3. 14. 09:34 | Posted in JavaScript & jQuery/jQuery
반응형




■ onMouseover를 통한 이미지 변경




# 소스코드

<html>
<title>:: 상품박스 ::</title>
<head>
<style type="text/css">
    .represent {
        border:1px solid #FF0000;
        width:460px;
        overflow:auto;
    }

    ul {
        list-style:outside none none;
        margin:0;
        padding:0;
    }

    li {
        margin:0 0 0 0;
        padding:0 0 0 0;
        border:0;
        float:left;
        width:20%;
    }

    img {
        width:100%;
    }
</style>
</head>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
function changeRepresentImage(num) {
    var link = jQuery(".imgServe").eq(num).attr("src");
    jQuery("#imgRepresent").attr("src", link);
}
</script>
<body>
    <div class="represent">
        <img id="imgRepresent" src="./image/Box_01.png" style="width:460px;height:460px;"/>
        <ul>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('0');">
                    <img class="imgServe" src="./image/Box_01.png"/>
                </a>
            </li>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('1');">
                    <img class="imgServe" src="./image/Box_02.png"/>
                </a>
            </li>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('2');">
                    <img class="imgServe" src="./image/Box_03.png"/>
                </a>
            </li>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('3');">
                    <img class="imgServe" src="./image/Box_04.png"/>
                </a>
            </li>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('4');">
                    <img class="imgServe" src="./image/Box_05.png"/>
                </a>
            </li>
        </ul>
    </div>
</body>
</html>



# 출력결과




인터넷 쇼핑몰등에서는 위와같이 상품의 대표이미지를 올려둘 수 있는 사이트들이 많이 있다.


이렇게 상품 이미지를 올리는것은


<input type="file"/>을 사용하는 것이 쉬울 수 있겠지만,


좀더 세련된 UI를 사용해 보기위해 아래와같은 방식을 취해 보려고 한다.







■ AJAX로 파일 업로드 하고 썸네일 이미지 받아오기




# 소스코드 - 이미지 업로드를 실제로 조작하는 thumbnail_upload.php

<html>
<title>:: 업로드 파일 썸네일 생성 ::</title>
<head>
<style type="text/css">
.temporaryFile {
    display:none;
}

.thumbnailImg {
    width:64px;
    height:64px;
    border-radius:10px;
    border:3px solid #CCCCCC;
}
</style>
</head>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
// 이미지를 업로드 할 준비를 시작한다.
function temporaryFileUpload(num) {

    // 이미지파일의 정보를 받을 배열을 선언한다.
    var tmpFile = new Object();
    tmpFile['file'] = new Array();     // tmpFile['file'] 파일의 정보를 담을 변수
    tmpFile['img'] = new Array();    // tmpFile['file'] 이미지의 경로를 담을 변수
    var tmpNum = 0;
    var addPlus = 0;

    // 먼저 업로드 된 파일의 존재 유무를 확인한다.
    if(jQuery(".temporaryFile").eq(num).val()) {

        // 파일이 존재하면 우선 기존 파일을 삭제한 이후에 작업을 진행한다.
        if(confirm("해당 이미지를 삭제 하시겠습니까?") == true) {

            // 먼저 업로드 하지 않을 파일을 제거한다.
            jQuery(".temporaryFile").eq(num).val("");

            // 파일이 제거되면 <input type="file"/>의 수만큼 반복문을 돌린다.
            jQuery(".temporaryFile").each(function(idx) {

                // 반복문을 돌리는 중에 <input type="file"/>의 값이 존재한는 순서로 배열에 담는다.
                if(jQuery(".temporaryFile").eq(idx).val()) {
                    tmpFile['file'][tmpNum] = [jQuery(".temporaryFile").eq(idx).clone()];
                    tmpFile['img'][tmpNum] = jQuery(".thumbnailImg").eq(idx).attr("src");
                    tmpNum++;
                }
            });
          
            // 모든 썸네일 이미지 정보를 초기화 한다.
            jQuery(".temporaryFile").val("");
            jQuery(".thumbnailImg").attr("src", "./plusimg.png");
            jQuery(".thumbnailImg").css("display", "none");
          

            // 배열로 받은 파일의 정보를 for문 or for in문을 사용하여 순서를 재정렬한다.


            /* ① for in 문을 사용한 경우(for in 문을 주석처리 한 이유는 아래에 기술 하였다.)

            for(var key in tmpFile['file']) {
                jQuery(".temporaryFile").eq(key).replaceWith(tmpFile['file'][key][0].clone(true));
                jQuery(".thumbnailImg").eq(key).css("display", "inline");
                jQuery(".thumbnailImg").eq(key).attr("src", tmpFile['img'][key]);
                addPlus++;
            }

            */

           

            /* for 문(ie8 이하 호환)을 사용한 경우 */

            for(var lineUp = 0, item; item=tmpFiles['file'][lineUp]; lineUp++) {
                jQuery(".temporaryFile").eq(lineUp).replaceWith(tmpFiles['file'][addPlus][0].clone(true));
                jQuery(".thumbnailImg").eq(lineUp).css("display", "inline");
                jQuery(".thumbnailImg").eq(lineUp).attr("src", tmpFiles['src'][addPlus]);
                jQuery(".previousFile").eq(lineUp).val(tmpFiles['img'][addPlus]);
                addPlus++;
            }

            if(addPlus < 5) {
                jQuery(".thumbnailImg").eq(addPlus).css("display", "inline");
            }

        } else {
            return false;
        }
    }
  
    // 파일이 존재하지 않다면 업로드를 시작한다.
    else {
        jQuery(".temporaryFile").eq(num).click();
    }
}

// 임시폴더에 파일을 업로드하고 그 경로를 받아온다.
function temporaryFileTransmit(num) {
    var form = jQuery("#uploadFrom")[0];
    var formData = new FormData(form);
    formData.append("mode", "temporaryImageUpload");
    formData.append("tmpFile", jQuery(".temporaryFile").eq(num)[0].files[0]);
  
    // ajax로 파일을 업로드 한다.
    jQuery.ajax({
          url : "./upload_class.php"
        , type : "POST"
        , processData : false
        , contentType : false
        , data : formData
        , success:function(json) {
            var obj = JSON.parse(json);
            if(obj.ret == "succ") {

                // 업로드된 버튼을 임시폴더에 업로드된 경로의 이미지 파일로 교체한다.
                jQuery(".thumbnailImg").eq(num).attr("src", obj.img);

                // 업로드 버튼이 4개 이하인경우 업로드 버튼을 하나 생성한다.
                if(num < 5) {
                    jQuery(".thumbnailImg").eq(++num).css("display", "inline");
                }

            } else {
                alert(obj.message);
                return false;
            }
        }
    });
}
</script>
<body>
<form id="uploadFrom" method="post">
<input type="file" class="temporaryFile" name="thumbnailImg[0]" onChange="temporaryFileTransmit(0);" style="display:none;"/>
<input type="file" class="temporaryFile" name="thumbnailImg[1]" onChange="temporaryFileTransmit(1);" style="display:none;"/>
<input type="file" class="temporaryFile" name="thumbnailImg[2]" onChange="temporaryFileTransmit(2);" style="display:none;"/>
<input type="file" class="temporaryFile" name="thumbnailImg[3]" onChange="temporaryFileTransmit(3);" style="display:none;"/>
<input type="file" class="temporaryFile" name="thumbnailImg[4]" onChange="temporaryFileTransmit(4);" style="display:none;"/>
<h1># 이미지 파일 업로드시 썸네일 생성하기</h1>
<table>
    <tr>
        <th>이미지 업로드 : </th>
        <td>
            <a href="javascript:;" onClick="temporaryFileUpload(0);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:inline;"/>
            </a>
            <a href="javascript:;" onClick="temporaryFileUpload(1);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:none;"/>
            </a>
            <a href="javascript:;" onClick="temporaryFileUpload(2);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:none;"/>
            </a>
            <a href="javascript:;" onClick="temporaryFileUpload(3);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:none;"/>
            </a>
            <a href="javascript:;" onClick="temporaryFileUpload(4);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:none;"/>
            </a>
        </td>
    </tr>
</table>
</form>
</body>
</html> 


※ for in 문을 주석 처리한 이유

 처음에 제작할때는 for in문을 사용했었다.
 그런데 문제가 발생한것이 필자는 평소 다음 오픈 에디터를 주로 사용하는데.
 다음 오픈 에디터와 같은 페이지에서 해당 반복문이 돌아갈 경우 스크립트 충돌이 발생했다.

 (이유는 아직 까지 확인 하지 못했다.)

 그래서 ② for 문(ie8 호환 방식)을 사용하게 되었다

 (위 코드는 그냥 for문을 사용해도 된다. 하지만 다른곳에서 문제가 발생하는 경우가 있었기에 적어둔다.)

 아무튼 다음 오픈 에디터와 같이 사용하는 경우에는 스크립트단에서의 for in 문의 사용은 자제하려 한다.

 



# 소스코드 - 임시 경로에 파일을 업로드 하고 업로드된 이미지를 받아오는 upload_class.php

<?php
// 업로드 폴더 경로
$uploadsDir = "./temporary";

// 업로드 가능한 확장자 지정
$allowedExt = array("jpg", "JPG", "jpeg", "JPEG", "png", "PNG", "gif", "GIF");

switch($_POST['mode']) {

    case "temporaryImageUpload" :

        $fileName = $_FILES['tmpFile']['name'];

        // 파일의 확장자를 분리
        $ext = array_pop(explode(".", $fileName));

        // 업로드 가능한 확장자 인지 확인한다.
        if(!in_array($ext, $allowedExt)) {
            $RetVal['message'] = "허용되지 않는 확장자입니다.";
        } else {

            // 업로드할 파일의 경로
            $tmpFile = $uploadsDir."/".date("YmdHis")."_".$fileName;

            if(move_uploaded_file($_FILES['tmpFile']['tmp_name'], $tmpFile)) {
                $RetVal['img'] = $tmpFile;
                $RetVal['ret'] = "succ";
            } else {
                $RetVal['message'] = "업로드시 문제가 발생하였습니다.\n다시 시도하여 주시기 바랍니다.";
            }
        }

        print json_encode($RetVal);
        return;
    break;

    default :
    break;
}
?>



# 출력결과






반응형
//