2011-09-01 2 views
0

아침 인사입니다.CodeIgniter (및 allowed_types) 문제

저는 CodeIgniter와 함께 Plupload를 사용하려고합니다. 나는 Plupload 전에 업로드를 시도했는데 두려웠다. 업로드 문제의 주요한 문제는 CSRF 코드를 보낸 적이 없다는 점이다. Plupload를 검토 한 결과, 정말 이상했다. 그러나 플래시 업 로더가 아닌 HTML5 업 로더에서만 잘 작동합니다.

로그 검토하기 CodeIgniter File Uploading Class를 사용하는 동안 작동하지 않는 이유를 발견했습니다.

내가 대량 이미지 업 로더를 제작할 때 "jpg, gif, png, jpeg"를 허용하도록 설정했기 때문에 잘못된 type_file을 업로드했기 때문에 업 로더가 업로드 탄원을 거부한다는 사실을 발견했습니다. octet/stream - wtf?).

업로드 프로세스가 끝난 후 이미지를 처리 ​​(엄지 손가락, 워터 마크, 자르기 등) 했으므로 모든 파일 형식을 허용하도록 설정하면 이미지 처리가 전혀 작동하지 않습니다.

파일 업로드 (옥텟/스트림 MIME TYPE 허용)와 같은 작업을하고 imagecreatefromstring 및 file_get_contents 함수를 사용하여 이미지로 변환 한 다음 개별적으로 처리하는 방법에 대해 생각했습니다.

당신이 다른 생각이 날에 가기 전에

답변

4

을 알려 있다면, 난 당신이 어떤 플래시 업 로더를 드롭, 항상 HTML5를 유지하고 하위 호환성 https://github.com/blueimp/jQuery-File-Upload을 선택하는 것이 좋습니다. 대부분의 경우 막대를 업로드 할 수는 없지만 Flash는 없으므로 CodeIgniter를 수정하지 않아도됩니다.

다음은별로 세련되지 않습니다. 사실, 다음 버전에서 내 응용 프로그램에 플래시 업로드에 대한 지원을 중단 할 예정입니다.

Flash를 통해 업로드 한 내용은 application/octet-stream으로 서버에 수신됩니다. /application/config/mime.php 파일에서 "application/octet-stream"을 원하는 파일 유형에 추가하면 문제가 발생하지 않습니다. 여기에 an example이 있으며, 파일의 맨 아래를보십시오.

현재 CSRF는 완전히 별개의 브라우저와 같은 의미로 Flash가 자체 쿠키를 가지고 있기 때문에 그다지 문제가되지 않습니다. CSRF를 보내려고하기 전에 CodeIgniter가 사용자를 식별하는 데 사용하는 세션 ID를 Flash에 넣어야합니다. 당신이 Uploadify3 (이 Uploadify 2 Plupload도 작동한다)를 사용하려는 경우 당신은 또한 당신이 먼저 추가해야 /application/config/config.php

$config['sess_match_useragent'] = FALSE; 

에서 변경해야합니다/응용 프로그램/라이브러리/POST를 통해 세션 데이터를 보낼 수 있도록 MY_Session.php. https://github.com/woxxy/FoOlSlide/blob/a7522d747fe406da18ce18ae9763f083b89eb91e/application/libraries/MY_Session.php

그런 다음 컨트롤러에, 당신이 그것을 가능 언제든지 세션 ID를 검색 할 수 있도록해야한다 :

그냥이 파일을 사용합니다.

function get_sess_id() 
{ 
    $this->output->set_output(json_encode(array('session' => $this->session->get_js_session(), 'csrf' => $this->security->get_csrf_hash()))); 
} 

업로드 컨트롤러는 꽤 표준적인 업로드 기능을 갖추고 있어야합니다. 업로드 할 때 올바른 이름 ("사용자 파일")을 사용했는지 확인하십시오.

이제 최악의 부분은보기 파일입니다.일부 세부 정보는 삭제할 수 있지만 추가 데이터가 있으면 Uploadify3에서 너무 많이 조회하지 않고 코딩하는 데 도움이 될 것입니다. 이미 충분히 작업 아니었다면

<script type="text/javascript"> 
    function updateSession() 
    { 
     jQuery.post('<?php echo site_url('/admin/series/get_sess_id'); ?>', 
     function(result){ 

      jQuery('#file_upload_flash').uploadifySettings('postData', { 
       'ci_sessionz' : result.session, 
       '<?php echo $this->security->get_csrf_token_name(); ?>' : result.csrf, 
       'chapter_id' : <?php echo $chapter->id; ?> 
      }, false); 
      setTimeout('updateSession()', 6000); 
     }, 'json'); 
    } 

    jQuery(document).ready(function() { 
     jQuery('#file_upload_flash').uploadify({ 
      'swf' : '<?php echo site_url(); ?>assets/uploadify/uploadify.swf', 
      'uploader' : '<?php echo site_url('/admin/series/upload/compressed_chapter'); ?>', 
      'cancelImage' : '<?php echo site_url(); ?>assets/uploadify/uploadify-cancel.png', 
      'checkExisting' : false, 
      'preventCaching' : false, 
      'multi' : true, 
      'buttonText' : '<?php echo _('Use flash upload'); ?>', 
      'width': 200, 
      'auto'  : true, 
      'requeueErrors' : true, 
      'uploaderType' : 'flash', 
      'postData' : {}, 
      'onSWFReady' : function() { 
       updateSession(); 
      }, 
      'onUploadSuccess' : function(file, data, response) { 
       var files = jQuery.parseJSON(data); 
       var fu = jQuery('#fileupload').data('fileupload'); 
       fu._adjustMaxNumberOfFiles(-files.length); 
       fu._renderDownload(files) 
       .appendTo(jQuery('#fileupload .files')) 
       .fadeIn(function() { 
        jQuery(this).show(); 
       }); 
      } 
     }); 
    }); 

</script> 
<div id="file_upload_flash"></div> 

지금 ... 그것은 하나 또는 콜백 두 가지를 트리거하지 않습니다 Uploadify3에 버그가있다. 당신은 그것을 작게를 할 수 있습니다 https://github.com/woxxy/FoOlSlide/blob/a7522d747fe406da18ce18ae9763f083b89eb91e/assets/uploadify/jquery.uploadify.js

:

다음은 코드의 고정 된 버전입니다.

그러나 jQuery-File-Upload를 사용하려면 어떻게해야합니까?

그러면 컨트롤러를 약간 조정해야합니다. 여기

function upload() 
{ 
    $info = array(); 

    // compatibility for flash uploader and browser not supporting multiple upload 
    if (is_array($_FILES['Filedata']) && !is_array($_FILES['Filedata']['tmp_name'])) 
    { 
     $_FILES['Filedata']['tmp_name'] = array($_FILES['Filedata']['tmp_name']); 
     $_FILES['Filedata']['name'] = array($_FILES['Filedata']['name']); 
    } 

    for ($file = 0; $file < count($_FILES['Filedata']['tmp_name']); $file++) 
    { 
     $valid = explode('|', 'png|zip|rar|gif|jpg|jpeg'); 
     if (!in_array(strtolower(substr($_FILES['Filedata']['name'][$file], -3)), $valid)) 
      continue; 

     if (!in_array(strtolower(substr($_FILES['Filedata']['name'][$file], -3)), array('zip', 'rar'))) 
      $pages = $this->files_model->page($_FILES['Filedata']['tmp_name'][$file], $_FILES['Filedata']['name'][$file], $this->input->post('chapter_id')); 
     else 
      $pages = $this->files_model->compressed_chapter($_FILES['Filedata']['tmp_name'][$file], $_FILES['Filedata']['name'][$file], $this->input->post('chapter_id')); 

     foreach ($pages as $page) 
     { 
      $info[] = array(
       'name' => $page->filename, 
       'size' => $page->size, 
       'url' => $page->page_url(), 
       'thumbnail_url' => $page->page_url(TRUE), 
       'delete_url' => site_url("admin/series/delete/page"), 
       'delete_data' => $page->id, 
       'delete_type' => 'POST' 
      ); 
     } 
    } 

    // return a json array 
    echo json_encode($info); 
    return true; 
} 


function get_file_objects() 
{ 
    // Generate JSON File Output (Required by jQuery File Upload) 
    header('Content-type: application/json'); 
    header('Pragma: no-cache'); 
    header('Cache-Control: private, no-cache'); 
    header('Content-Disposition: inline; filename="files.json"'); 

    $id = $this->input->post('id'); 
    $chapter = new Chapter($id); 
    $pages = $chapter->get_pages(); 
    $info = array(); 
    foreach ($pages as $page) 
    { 
     $info[] = array(
      'name' => $page['filename'], 
      'size' => intval($page['size']), 
      'url' => $page['url'], 
      'thumbnail_url' => $page['thumb_url'], 
      'delete_url' => site_url("admin/series/delete/page"), 
      'delete_data' => $page['id'], 
      'delete_type' => 'POST' 
     ); 
    } 

    echo json_encode($info); 
    return true; 
} 

을 (나는 그것이 아마 어쨌든 깨진 업로드 컨트롤러를 만들 것 같은 중이 코드를 청소 통과하지 않습니다) 그리고 더 엄청난보기 코드를 추가하는 예이다 (이 시간은 jQuery를 업로드에서 거의 재고 하나)

<div id="fileupload"> 
    <link href="<?php echo site_url(); ?>assets/jquery-file-upload/jquery-ui.css" rel="stylesheet" id="theme" /> 
    <link href="<?php echo site_url(); ?>assets/jquery-file-upload/jquery.fileupload-ui.css" rel="stylesheet" /> 
    <?php echo form_open_multipart(""); ?> 
    <div class="fileupload-buttonbar"> 
     <label class="fileinput-button"> 
      <span>Add files...</span> 
      <input type="file" name="Filedata[]" multiple> 
     </label> 
     <button type="submit" class="start">Start upload</button> 
     <button type="reset" class="cancel">Cancel upload</button> 
     <button type="button" class="delete">Delete files</button> 
    </div> 
    <?php echo form_close(); ?> 
    <div class="fileupload-content"> 
     <table class="files"></table> 
     <div class="fileupload-progressbar"></div> 
    </div> 
</div> 
<script id="template-upload" type="text/x-jquery-tmpl"> 
    <tr class="template-upload{{if error}} ui-state-error{{/if}}"> 
     <td class="preview"></td> 
     <td class="name">${name}</td> 
     <td class="size">${sizef}</td> 
     {{if error}} 
     <td class="error" colspan="2">Error: 
      {{if error === 'maxFileSize'}}File is too big 
      {{else error === 'minFileSize'}}File is too small 
      {{else error === 'acceptFileTypes'}}Filetype not allowed 
      {{else error === 'maxNumberOfFiles'}}Max number of files exceeded 
      {{else}}${error} 
      {{/if}} 
     </td> 
     {{else}} 
     <td class="progress"><div></div></td> 
     <td class="start"><button>Start</button></td> 
     {{/if}} 
     <td class="cancel"><button>Cancel</button></td> 
    </tr> 
</script> 
<script id="template-download" type="text/x-jquery-tmpl"> 
    <tr class="template-download{{if error}} ui-state-error{{/if}}"> 
     {{if error}} 
     <td></td> 
     <td class="name">${name}</td> 
     <td class="size">${sizef}</td> 
     <td class="error" colspan="2">Error: 
      {{if error === 1}}File exceeds upload_max_filesize (php.ini directive) 
      {{else error === 2}}File exceeds MAX_FILE_SIZE (HTML form directive) 
      {{else error === 3}}File was only partially uploaded 
      {{else error === 4}}No File was uploaded 
      {{else error === 5}}Missing a temporary folder 
      {{else error === 6}}Failed to write file to disk 
      {{else error === 7}}File upload stopped by extension 
      {{else error === 'maxFileSize'}}File is too big 
      {{else error === 'minFileSize'}}File is too small 
      {{else error === 'acceptFileTypes'}}Filetype not allowed 
      {{else error === 'maxNumberOfFiles'}}Max number of files exceeded 
      {{else error === 'uploadedBytes'}}Uploaded bytes exceed file size 
      {{else error === 'emptyResult'}}Empty file upload result 
      {{else}}${error} 
      {{/if}} 
     </td> 
     {{else}} 
     <td class="preview"> 
      {{if thumbnail_url}} 
      <a href="${url}" target="_blank"><img src="${thumbnail_url}"></a> 
      {{/if}} 
     </td> 
     <td class="name"> 
      <a href="${url}"{{if thumbnail_url}} target="_blank"{{/if}}>${name}</a> 
     </td> 
     <td class="size">${sizef}</td> 
     <td colspan="2"></td> 
     {{/if}} 
     <td class="delete"> 
      <button data-type="${delete_type}" data-url="${delete_url}" data-id="${delete_data}">Delete</button> 
     </td> 
    </tr> 
</script> 
<script src="<?php echo site_url(); ?>assets/js/jquery-ui.js"></script> 
<script src="<?php echo site_url(); ?>assets/js/jquery.tmpl.js"></script> 
<script src="<?php echo site_url(); ?>assets/jquery-file-upload/jquery.fileupload.js"></script> 
<script src="<?php echo site_url(); ?>assets/jquery-file-upload/jquery.fileupload-ui.js"></script> 
<script src="<?php echo site_url(); ?>assets/jquery-file-upload/jquery.iframe-transport.js"></script> 

<script type="text/javascript"> 

    jQuery(function() { 
     jQuery('#fileupload').fileupload({ 
      url: '<?php echo site_url('/admin/series/upload/compressed_chapter'); ?>', 
      sequentialUploads: true, 
      formData: [ 
       { 
        name: 'chapter_id', 
        value: <?php echo $chapter->id; ?> 
       } 
      ] 
     }); 

     jQuery.post('<?php echo site_url('/admin/series/get_file_objects'); ?>', { id : <?php echo $chapter->id; ?> }, function (files) { 
      var fu = jQuery('#fileupload').data('fileupload'); 
      fu._adjustMaxNumberOfFiles(-files.length); 
      fu._renderDownload(files) 
      .appendTo(jQuery('#fileupload .files')) 
      .fadeIn(function() { 
       jQuery(this).show(); 
      }); 

     }); 

     jQuery('#fileupload .files a:not([target^=_blank])').live('click', function (e) { 
      e.preventDefault(); 
      jQuery('<iframe style="display:none;"></iframe>') 
      .prop('src', this.href) 
      .appendTo('body'); 
     }); 

    }); 

</script> 
+0

우수 답변, 매우 상세하고 이제 모든 문제를 명확하게 이해합니다. 분명히 HTML5 업 로더를 선호하지만, 일부 경우 (예전 브라우저) 플래시 지원이 필요합니다. Uploadify 3을 사용해 보았지만 업 로더를 시작하지 않았습니다. 나는 모든 것을 다시 시도하고 알려주지. – demogar