티스토리 뷰
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <!doctype html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta name="Author" content="http://webdevelop.tistory.com/"> <title>Document</title> <script src='js/jquery-1.7.2.min.js'></script> </head> <body> <form action="view.php" method="post"> <textarea id="content" name="content"></textarea> <input type="submit" value="전송"> </form> <form id="img_upload_form" action="img_upload.php" enctype="multipart/form-data" method="post" style="display:none;"> <input type='file' id="img_file" multiple="multiple" name='imgfile[]' accept="image/*"> </form> <div id="ajaxImageModal" style="display:none;"> <div id="light" style="display: table;position: absolute;top:25%;left:25%;width:50%;height:50%; text-align:center; background-color:transparent; z-index:1002;overflow: auto;"> <div style="display: table-cell; vertical-align: middle;"> <img src="js/ckeditor/plugins/ajaximage/loading.gif" style="user-select: none; -ms-user-select: none;"> </div> </div> </div> <script src="js/jquery.form.min.js"></script> <script src="js/ckeditor/ckeditor.js"></script> <script src="js/ckeditor/adapters/jquery.js"></script> <script> $('#content').ckeditor(); //객체 생성 var ajaxImage = {}; // ckeditor textarea id ajaxImage["id"] = "content"; // 업로드 될 디렉토리 ajaxImage["uploadDir"] = "upload"; // 한 번에 업로드할 수 있는 이미지 최대 수 ajaxImage["imgMaxN"] = 10; // 허용할 이미지 하나의 최대 크기(MB) ajaxImage["imgMaxSize"] = 20; </script> </body> </html> | cs |
#img_upload_form는 textarea의 폼과 다른 영역에 있어야한다.
#ajaxImageModal는 데이터 전송시 나오는 로딩이미지이다.
js/ckeditor/plugins/ajaximage/plugin.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | CKEDITOR.plugins.add('ajaximage', { init: function (editor) { var pluginName = 'ajaximage'; editor.ui.addButton('Ajaximage', { label: '이미지 업로드', command: 'OpenWindow', icon: CKEDITOR.plugins.getPath('ajaximage') + 'ajaximage.gif' }); var cmd = editor.addCommand('OpenWindow', { exec: showMyDialog }); } }); function showMyDialog(e) { $('#img_file').trigger("click"); } $("#img_file").change(function(){ var dot_pos; var ext; var allowed_ext = ['jpg','jpeg','png','gif']; if(this.files.length > ajaxImage["imgMaxN"]){ this.value = ""; alert("이미지는 한번에 최대 " + ajaxImage["imgMaxN"] + "개까지 업로드할 수 있습니다."); return; } for(var i=0; i < this.files.length ; i++){ dot_pos = this.files[i].name.lastIndexOf("."); ext = this.files[i].name.substr(dot_pos+1,3).toLowerCase(); if(allowed_ext.indexOf(ext) == -1){ this.value = ""; alert("허용되지 않는 확장자입니다."); return; } } for(var i=0; i < this.files.length ; i++){ if(this.files[i].size > ajaxImage["imgMaxSize"]*1024*1024){ this.value = ""; alert("이미지 하나의 최대 크기는 " + ajaxImage["imgMaxSize"] + "MB입니다."); return; } } if(this.files.length >= 1){ $('#img_upload_form').submit(); $('#img_file').val(''); } }); $('#img_upload_form').ajaxForm({ type: "POST", dataType: 'json', beforeSend: function() { $("#ajaxImageModal").show(); }, complete: function(data) { var result = JSON.parse(JSON.parse(JSON.stringify(data))["responseText"]); if(result["status"] == "OK"){ var imgData = ""; for (var i=0; i<result["crypto"].length ; i++ ){ imgData += "<p><img src='"+ ajaxImage["uploadDir"] + "/" + result["crypto"][i] + "' alt='" + result["name"][i] +"'></p>"; } var originData = CKEDITOR.instances[ajaxImage.id].getData(); CKEDITOR.instances[ajaxImage.id].setData(originData + imgData); }else{ alert(result["message"]); } $("#ajaxImageModal").hide(); }, error: function(request,status,error){ alert("이미지를 업로드하지 못했습니다."); //alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error); } }); | cs |
이미지 버튼을 클릭했을때 input file을 클릭한다.
input file의 value가 바뀌면 이미지들을 체크한 후에
ajaxForm을 이용하여 이미지를 보낸다.
img_upload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | <?php // 업로드 될 디렉토리 (권한 777) $uploads_dir = 'upload'; // 한 번에 업로드할 수 있는 이미지 최대 수 $imgMaxN = 10; // 허용할 이미지 하나의 최대 크기(MB) $imgMaxSize = 20; if( !isset($_FILES['imgfile']['error']) ) { echo json_encode( array( 'status' => 'error', 'message' => '파일이 첨부되지 않았습니다.' )); exit; } for($i=0; $i < count($_FILES['imgfile']['name']) ; $i++){ $error = $_FILES['imgfile']['error'][$i]; if( $error != UPLOAD_ERR_OK ) { switch( $error ) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $message = "파일이 너무 큽니다. ($error)"; break; case UPLOAD_ERR_NO_FILE: $message = "파일이 첨부되지 않았습니다. ($error)"; break; default: $message = "파일이 제대로 업로드되지 않았습니다. ($error)"; } echo json_encode( array( 'status' => 'error', 'message' => $message )); exit; } } if( count($_FILES['imgfile']['name']) > $imgMaxN ){ echo json_encode( array( 'status' => 'error', 'message' => '이미지는 한번에 최대 '.$imgMaxN.'개까지 업로드할 수 있습니다.' )); exit; } $allowed_ext = array('jpg','jpeg','png','gif'); for($i=0; $i < count($_FILES['imgfile']['name']) ; $i++){ $name = $_FILES['imgfile']['name'][$i]; $ext = strtolower(substr(strrchr($name, '.'), 1)); // 확장자 확인 if( !in_array($ext, $allowed_ext) ) { echo json_encode( array( 'status' => 'error', 'message' => '허용되지 않는 확장자입니다.' )); exit; } // 파일 사이즈 검사 if( $_FILES['imgfile']['size'][$i] > $imgMaxSize*1024*1024 ){ echo json_encode( array( 'status' => 'error', 'message' => '이미지 하나의 최대 크기는 '.$imgMaxSize.'MB입니다.' )); exit; } // 변환될 파일명 $crypto[$i] = date("YmdHis",time())."_".md5($name).".".$ext; } //이미지인지 체크(확장자만 이미지일 수 있어서) for($i=0; $i < count($_FILES['imgfile']['name']) ; $i++){ $pathNname[$i] = $uploads_dir."/".$crypto[$i]; move_uploaded_file( $_FILES['imgfile']['tmp_name'][$i], $pathNname[$i]); $info = getimagesize($pathNname[$i]); $width[$i] = $info[0]; if(!($width[$i] > 0)){ echo json_encode( array( 'status' => 'error', 'message' => '업로드에 실패했습니다.' )); exit; } } echo json_encode( array( 'status' => 'OK', 'name' => $_FILES['imgfile']['name'], 'crypto' => $crypto, //'ext' => $ext, //'type' => $_FILES['imgfile']['type'], //'size' => $_FILES['imgfile']['size'], //'pathNname' => $pathNname, //'width' => $width )); ?> | cs |
json 형식으로 결과를 내보내준다.
(upload 디렉토리 권한이 777이어야한다.)
javascript 업로드 디렉토리와 php에 업로드 디렉토리를 잘 설정해야한다.
php에 업로드 디렉토리를 가져와서 javascript에 뿌려주면 안되더라.. 절대경로문제
win10 크롬,익스플러어11,익스플로어엣지,파이어폭스
갤럭시s7 크롬,
아이폰4 크롬,사파리에서 이상 없었다.
macOS 사파리에서 이상없었다. //19.11.20 확인
ckeditor_imageupload_ver0.5.zip
참고
https://zetawiki.com/wiki/JQuery_Ajax_파일업로드_자동제출
'공개' 카테고리의 다른 글
공기계에 웹서버를 구축해보자(4) (2) | 2018.02.18 |
---|---|
[PHP5]ckeditor ajax 이미지 다중 업로드 기능을 추가해보자(1) (0) | 2017.12.06 |
공기계에 웹서버를 구축해보자(3) (1) | 2017.11.09 |
공기계에 웹서버를 구축해보자(2) (0) | 2017.11.07 |
공기계에 웹서버를 구축해보자(1) (1) | 2017.11.07 |
댓글