CI 묻고 답하기

제목 ...허접초보 프로그래머의 질문 2입니다...
글쓴이 느림보 작성시각 2012/01/28 13:09:06
댓글 : 6 추천 : 0 스크랩 : 0 조회수 : 20754   RSS
이번엔 주저리주저리...말이 많습니다....죄송합니다...

현재 이미지 업로드 부분을 진행중에 있습니다....

iframe을 이용하여 ajax 이미지 업로드를 구현하였고

jquery.form.js를 이용하여 좀더 쉽게 ajax이미지 업로드를 구현하였습니다.....

그런데 이러한 방식이 문제가 있는게;;;

사실 미리보기를 구현하려고 ajax를 이용하여 페이지 리로딩 없이 이미지를 띄우려고 하다보니

요청을 할때마다 이미지가 쌓여서 막상 쓰지도 않는 이미지가 계속 쌓이니까

용량이 점점 커지더라구요;;;ㅎ 그래서 열심히 구글링을 한결과...

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[removed] = "";
        var W = preViewer.offsetWidth;
        var H = preViewer.offsetHeight;
        var tmpImage = document.createElement("img");
        preViewer.appendChild(tmpImage);

        tmpImage.onerror = function () {
            return preViewer[removed] = "";
        }

        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;
        }
    }
}
요런 로직을 발견을 하였습니다...

그런데 요게 작동원리를 모르겠더라구요...ㅎ

제가 대충 독학으로 알아본 결과는...브라우저 마다 이미지를 보여주는 방식이 다르다는 것과

ie에서는 보안문제로 직접적으로 이미지 경로를 찍어주면

fakepath가 찍혀서 제대로 안보여져서 fakepath만 빼고 image로더를 이용하여 

이미지를 찍어주고

그리고 실제론 이미지는 업로드가 안된상태에서 보여주는 것 까지만 알아낸 상태이네요

;;그런데 이게 어떠한 원리로 찍히는건지 서버에 과부하가 얼마나 걸리는 건지.. 알려주시면 감사하겠습니다...

두번째 질문은 현재 이미지 업로드는 구현한 상태인데 다중 업로드가 아니라 하나만 업로드 할수 있는 기능입니다....

음....예를 들자면 flash의 dialogbox를 이용하면 파일을 다중으로 선택할수 있는데 input type="file"은

한개밖에 파일이 선택이 안되더라구요...html5에서는
 
input type="file" multiple를 사용하면 된다는데 ie8에서는 html5가 지원이 안되는

모양인지.... 아무리 저 태그를 써봐도 파일이 다중선택이 안되더라구요...

...홈페이지에 플래쉬를 하나도 쓰지 않겠다라는 제 신념이 꺽일지경에 놓인 상태입니다...ㅜㅜ

마지막으로 input type="file"의 찾아 보기 버튼을 이미지로 변환한 소스인데요....

filebutton.js
function FileButton(imageswap, imagesrc)
{
 this.imageswap = imageswap;
 this.imagesrc = imagesrc;
 this.swapnode = document.getElementsByTagName("INPUT");
 this.filebox = document.createElement("DIV");
 this.filebox.style.width = "0px";
 this.filebox.style.height = "0px";
 this.filebox.style.position = "relative";
 this.filebox.style.overflow = "hidden";
}
FileButton.prototype =
{
 getBounds: function (tag) {
  var ret = new Object();
  if (tag.getBoundingClientRect) {
   var rect = tag.getBoundingClientRect();
   ret.left = rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft);
   ret.top = rect.top + (document.documentElement.scrollTop || document.body.scrollTop);
   ret.width = rect.right - rect.left;
   ret.height = rect.bottom - rect.top;
  } else if (document.getBoxObjectFor) {
   var box = document.getBoxObjectFor(tag);
   ret.left = box.x;
   ret.top = box.y;
   ret.width = box.width;
   ret.height = box.height;
  } else {
   ret.left = tag.offsetLeft;
   ret.top = tag.offsetTop;
   ret.width = tag.offsetWidth;
   ret.height = tag.offsetHeight;
  }
  if (navigator.appName == "Microsoft Internet Explorer") {
   ret.left -= 2;
   ret.top -= 2;
  }
  return ret;
 },
 swap: function (swapnode) {
  var This = this;
  var filebox = this.filebox.cloneNode(true);
  var image = new Image();
  var imageurl = swapnode.getAttribute(this.imagesrc);
  swapnode[removed].insertBefore(filebox, swapnode);
  filebox.appendChild(swapnode);
  filebox.appendChild(image);
  filebox.style.width = this.getBounds(swapnode).width + "px";
  filebox.style.height = this.getBounds(swapnode).height + "px";
  image.onload = function () {
   this[removed].style.backgroundImage = "url(" + this.previousSibling.getAttribute(This.imagesrc) + ")";
   this[removed].style.backgroundRepeat = "no-repeat";
   this[removed].style.width = this.width + "px";
   this[removed].style.height = this.height + "px";
   this.previousSibling.style.filter = "alpha(opacity=0)";
   this.previousSibling.style.opacity = 0;
   this.previousSibling.style.fontSize = (Math.max(this.width, this.height) + 30) + "px";
   this.previousSibling.style.position = "relative";
   this.previousSibling.style.height = (this.height + 30) + "px";
   this.previousSibling.style.left = (0 - This.getBounds(this.previousSibling).width) + "px";
   this.previousSibling.style.top = "-10px";
   
   var parentnode = this[removed];
   var divForGetHTML = filebox.cloneNode(false);
   divForGetHTML.appendChild(this.previousSibling);
   parentnode[removed] = divForGetHTML[removed];

   var fileright = This.getBounds(parentnode.firstChild).left + This.getBounds(parentnode.firstChild).width;
   var boxright = This.getBounds(parentnode).left + This.getBounds(parentnode).width;
   if (fileright < boxright) {
    parentnode.firstChild.style.left = (This.getBounds(parentnode.firstChild).left + boxright) + "px";
   }

   divForGetHTML = null;
   parentnode.firstChild.setAttribute(This.imageswap, "swapped");
  }
  image.src = swapnode.getAttribute(this.imagesrc);
 },
 write: function (source) {
  var spanid = "spanforFileButton" + new Date().getTime();
  [removed]('<span id="' + spanid + '">' + source + '</span>');
  var span = document.getElementById(spanid);
  this.swap(span.firstChild);
  span[removed].insertBefore(span.firstChild, span);
  span = null;
 },
 run: function () {
  for (var i = 0; i < this.swapnode.length; i++) {
   var swapnode = this.swapnode[i];
   if (swapnode.type == "file" && swapnode.getAttribute(this.imageswap) == "true") {
    this.swap(swapnode);
   }
  }
 }
}
그리고 이건
페이지 윗부분에 들어가는 온로드 부분입니다.
<script type="text/javascript"> 
var myFileButton = new FileButton("imageswap", "imagesrc");
window.onload = function () {
}
view페이지 입니다.
<table width="646" border="0" cellspacing="0" cellpadding="0"  id="6">
    <tr>
         <td>
          <div id="preView" class="preView" title="이미지미리보기" style="width:100px; height:100px;"><img src="<?=IMAGE_SRC?>/mycar/profile.gif"></div>
 </td>
         <td rowspan="2"></td>
    </tr>
    <tr>
         <td>
              <div class="nonl">
                   <script type="text/javascript">
       myFileButton.write('<input type="file" accept="image/*" name="uploadfile" imageswap="true" imagesrc="<?=IMAGE_SRC?>/button-5.gif" onmousedown="this[removed].style.backgroundPosition=\'2px 2px\';"       onmouseup="this[removed].style.backgroundPosition=\'0px 0px\';" onchange="fileUploadPreview(this, \'preView\');" />');
   </script>
      </div>
 </td>
    </tr>
</table>
사실 예전에 쓰던방식중에 하나가 이미지나 버튼을 onclick="$('input file').click() 요런식으로 대체해서 쓰다보니

submit할때 보안에 위배되는지 파일에 내용지 지워지고 엑세스 거부 반응을 표시 하더라구요...

아까 위에 있던 미리보기 부분하구

지금 보시는 찾아 보기 버튼 바꾸는 기능 두개를 짬뽕해서 쓰다 보니 쓸때 없는 파일이 쌓이는

부분과 보기싫은 찾아 보기 버튼을 바꾸는 두마리의 토끼를 잡을수 있겠더라구요

그런데 이소스 들이 실제 서버에서 얼마나 많은 과부하를 생성해 낼지와 

잘알지도 못하는데 아 되는 구나 하고 그냥 넘어 갈수가 없겠더라구요....

제 글을 한번 읽어 주시고 답변 부탁드리겠습니다 ㅜㅜ

p.s:....php codeIgniter의 질문이 아닌점 죄송합니다...


 다음글 uploadify 관련된 글입니다. (3)
 이전글 CI 완전 초보 코드 분석 도와주세요;; (4)

댓글

느림보 / 2012/01/28 13:10:18 / 추천 0
....아이고 정리 해서 올린다고 했는데 코드가 엉망 진창이네요..ㅜㅜ
변종원(웅파) / 2012/01/28 13:40:01 / 추천 0
첫번째는 서버에 어떤 액션이 있다면 부하가 가겠지만 클라이언트에서 액션이 일어난다면 서버랑은 상관이 없습니다.
변종원(웅파) / 2012/01/28 13:44:52 / 추천 0
그리고 서버부하는 외부에서는 경험상 이정도겠다밖에 이야기할 수가 없습니다. 파폭 파이어버그에서 net탭에서 걸리는 시간이나 전송량, 서버의 메모리, cpu사용률을 내부에서 체크하는 것이 제일 좋습니다
느림보 / 2012/01/28 13:51:04 / 추천 0
http watch 로 현재 확인중에 있습니다만 로컬에서 돌린 내용만 나오는지라...외부에서 확인하면 좀더 확실하게 아 이 서버는 과부하가 엄청 걸리는구나 라는걸로 알수 있는 건가요??ㅎ;;;

현재 linux서버로 돌리고 있는게 아니라 그냥 윈도우 os에 xampp만 설치해서 아파치로 돌리고 있거든요..ㅎ
느림보 / 2012/01/28 13:52:44 / 추천 0
그리구 가장궁금한것은...이미지 다중선택이 ie8에서 flash를 이용하지 않고도 이루어 질수  있는지가
가장 궁금합니다..ㅎ
느림보 / 2012/01/28 19:37:41 / 추천 0

ㅜㅜ 결국...uploadify를 이용하여 파일 업로드를 만들고 있습니다...그런데 이것도 그렇게 쉬운게 아니네요 ㅎㅎ;;