본문 바로가기

카테고리 없음

[AJAX] 파일 업로드 하고 썸네일 생성하기

반응형




■ 파일 업로드 하고 썸네일 생성하기



# 소스코드 01

 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(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++;
            }

            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>




# 소스코드 02

 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;
}
?>




# 출력결과




반응형