이미지 업로드전 미리보기 스크립트코드...
일반적인 방식으로는 ie만 지원되나 아래코드로 파이어폭스, ie8버전까지 지원되는것을 확인했다.
단, 크롬은 지원안됨..

<html>
<head>
    <title></title>
    <style type="text/css">
        .preView { width: 150px; height: 150px; 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="file" name="file" type="file" onchange="fileUploadPreview(this, 'preView')" />
    <div id="preView" class="preView" title="이미지미리보기"></div>
</body>
</html>


'Language > JavaScript' 카테고리의 다른 글

[Ajax] iframe 과의 요소 접근  (0) 2012.09.17
[텍스트 에디터] notepad++  (0) 2010.11.30
[JavaScript] Class 정의  (0) 2010.11.26
[Ajax] jQuery를 사용한 Ajax 구현  (0) 2009.12.29
javascript minifier  (0) 2009.12.03
Posted by finewoo
,