이미지 파일 첨부할 때 이미지 미리보기 기능을 구현하다가 막혀서 구글링 중에 찾은 포스팅인데
더 수정할 필요 없이 바로 사용해도 무리없는 소스를 발견하여 스크랩하여 둔다.

<html>
<head>
    <title></title>
    <style type="text/css">
        .preView { width: 70px; height: 70px; text-align: center; border:1px solid silver; }
    </style>
    <script type="text/javascript">

        function fileUploadPreview(thisObj, preViewer) {
            if(!/(\.gif|\.jpg|\.jpeg|\.png)$/i.test(thisObj.value)) {
                alert("이미지 형식의 파일을 선택하십시오");
                return;
            }

            preViewer = (typeof(preViewer) == "object") ? preViewer : document.getElementById(preViewer);
            var ua = window.navigator.userAgent;

            if (ua.indexOf("MSIE") > -1) {
                var img_path = "";
                if (thisObj.value.indexOf("\\fakepath\\") < 0) {
                    img_path = thisObj.value;
                } else {
                    thisObj.select();
                    var selectionRange = document.selection.createRange();
                    img_path = selectionRange.text.toString();
                    thisObj.blur();
                }
                preViewer.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='fi" + "le://" + img_path + "', sizingMethod='scale')";
            } else {
                preViewer.innerHTML = "";
                var W = preViewer.offsetWidth;
                var H = preViewer.offsetHeight;
                var tmpImage = document.createElement("img");
                preViewer.appendChild(tmpImage);

                tmpImage.onerror = function () {
                    return preViewer.innerHTML = "";
                }

                tmpImage.onload = function () {
                    if (this.width > W) {
                        this.height = this.height / (this.width / W);
                        this.width = W;
                    }
                    if (this.height > H) {
                        this.width = this.width / (this.height / H);
                        this.height = H;
                    }
                }
                if (ua.indexOf("Firefox/3") > -1) {
                    var picData = thisObj.files.item(0).getAsDataURL();
                    tmpImage.src = picData;
                } else {
                    tmpImage.src = "file://" + thisObj.value;
                }
            }
        }

    </script>
</head>
<body>
    <input id="fileData" name="fileData" type="file" onchange="fileUploadPreview(this, 'preView')" />
    <div id="preView" class="preView" title="이미지미리보기"></div>
</body>
</html>

출처 : Junyong's blog - http://junyong.pe.kr/98

'Dev > Javascript' 카테고리의 다른 글

Prototype에서 jQuery로 옮겨타기  (0) 2011.07.31
Firebug의 console 파헤치기.  (0) 2011.07.19
fireBug 사용법  (0) 2011.07.19
[jQuery] firebug로 디버그  (0) 2011.07.19
Javascript 배열 메서드  (0) 2011.04.29

+ Recent posts