2017-11-17 10 views
0

http://scottcheng.github.io/cropit/ 확장자를 사용하여 이미지를 자르려 고 시도했습니다 (OpenCart 3). 하지만 직렬화 된 이미지 데이터를 업로드하는 방법을 모르겠습니다.jquery/php에서 직렬화 된 이미지 데이터를 업로드하는 방법은 무엇입니까?

<form action="#"> 
    <div class="image-editor"> 
     <input type="file" class="cropit-image-input"> 
     <div class="cropit-preview"></div> 
     <div class="image-size-label"> 
      Resize image 
     </div> 
     <input type="range" class="cropit-image-zoom-input"> 
     <input type="hidden" name="image-data" class="hidden-image-data" /> 
     <button type="submit"><i class="fa fa-upload"></i> Submit</button> 
    </div> 
</form> 

<div id="result"> 
    <code>$form.serialize() =</code> 
    <code id="result-data"></code> 
</div> 

그리고 JQuery와/아약스 스크립트 : 여기

실제로 Cropit 확장 코드 코드의 HTML 부분입니다

<script> 
$(function() { 
    $('.image-editor').cropit(); 

    $('form').submit(function() { 

     // Move cropped image data to hidden input 
     var imageData = $('.image-editor').cropit('export'); 
     $('.hidden-image-data').val(imageData); 

     // Print HTTP request params 
     var formValue = $(this).serialize(); 
     $('#result-data').text(formValue); 

     //^ the codes of Cropit extension 
     // v the codes of PHP/OC3 for uploading images 

     $('#form-upload').remove(); 

     $('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file[]" value="" multiple="multiple" /></form>'); 

     if (typeof timer != 'undefined') { 
       clearInterval(timer); 
     } 

     timer = setInterval(function() { 
      if (imageData != '') { 
       clearInterval(timer); 

       $.ajax({ 
        url: 'index.php?route=common/filemanager/upload&user_token={{ user_token }}&directory={{ directory }}', 
        type: 'post', 
        dataType: 'json', 
        data: FormData(formValue), //new FormData($('#form-upload')[0]), 
        cache: false, 
        contentType: false, 
        processData: false, 
        beforeSend: function() { 
         $('#button-upload i').replaceWith('<i class="fa fa-circle-o-notch fa-spin"></i>'); 
         $('#button-upload').prop('disabled', true); 
        }, 
        complete: function() { 
         $('#button-upload i').replaceWith('<i class="fa fa-upload"></i>'); 
         $('#button-upload').prop('disabled', false); 
        }, 
        success: function(json) { 
         if (json['error']) { 
          alert(json['error']); 
         } 

         if (json['success']) { 
          alert(json['success']); 

          $('#button-refresh').trigger('click'); 
         } 
        }, 
        error: function(xhr, ajaxOptions, thrownError) { 
         alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); 
        } 
       }); 
      } 
     }, 500); 

     // Prevent the form from actually submitting 
     return false; 
    }); 
}); 
</script> 

그것은 흥미로운 페이지가 표시되는지 successful image upload 메시지 제출 버튼을 클릭하면 파일이 업로드되지만 실제로 업로드되지는 않습니다.

UPDATE : 추가 정보 여기에

는 PHP 업로드 기능입니다 :이 오류를 반환

<?php 
    public function upload() { 
     $json = array(); 

     // Make sure we have the correct directory 
     if (isset($this->request->get['directory'])) { 
      $directory = rtrim(DIR_IMAGE . 'catalog/' . $store_folder_slash . $this->request->get['directory'], '/'); 
     } else { 
      $directory = DIR_IMAGE . 'catalog' . $store_slash_folder; 
     } 

     // Check its a directory 
     if (!is_dir($directory) || substr(str_replace('\\', '/', realpath($directory)), 0, strlen(DIR_IMAGE . 'catalog' . $store_slash_folder)) != str_replace('\\', '/', DIR_IMAGE . 'catalog' . $store_slash_folder)) { 
      $json['error'] = $this->language->get('error_directory'); 
     } 

     if (!$json) { 
      // Check if multiple files are uploaded or just one 
      $files = array(); 

//   if (!empty($this->request->files['file']['name']) && is_array($this->request->files['file']['name'])) { 
//    foreach (array_keys($this->request->files['file']['name']) as $key) { 
//     $files[] = array(
//      'name'  => $this->request->files['file']['name'][$key], 
//      'type'  => $this->request->files['file']['type'][$key], 
//      'tmp_name' => $this->request->files['file']['tmp_name'][$key], 
//      'error' => $this->request->files['file']['error'][$key], 
//      'size'  => $this->request->files['file']['size'][$key] 
//     ); 
//    } 
//   } 

//   foreach ($files as $file) { 
//    if (is_file($file['tmp_name'])) { 
      if ($this->request->server['REQUEST_METHOD'] == 'POST') { 
       // Sanitize the folder name 
       $encoded = html_entity_decode($this->request->post['data'], ENT_QUOTES, 'UTF-8'); 

       //decode the url, because we want to use decoded characters to use explode 
       $decoded = urldecode($encoded); 

       //explode at ',' - the last part should be the encoded image now 
       $exp = explode(',', $decoded); 

       //we just get the last element with array_pop 
       $base64 = array_pop($exp); 

       //decode the image and finally save it 
       $data = base64_decode($base64); 

       if (is_file($data)) { 
        // Sanitize the filename 
        $filename = basename('test.jpg'); 
        //$filename = basename(html_entity_decode($file['name'], ENT_QUOTES, 'UTF-8')); 

        if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) { 
         $json['error'] = $this->language->get('error_filetype'); 
        } 
       } else { 
        $json['error'] = $this->language->get('error_upload'); 
       } 

       if (!$json) { 
        //move_uploaded_file($file, $directory . '/' . $filename); 
        file_put_contents($data, $directory . '/' . $filename); 
       } 
      } 
     } 

     if (!$json) { 
      $json['success'] = $this->language->get('text_uploaded'); 
     } 

     $this->response->addHeader('Content-Type: application/json'); 
     $this->response->setOutput(json_encode($json)); 
    } 

: 그것을 파악하는 방법
PHP Warning: is_file() expects parameter 1 to be a valid path, string given

없음 아이디어!

+0

일련화된 데이터는 파일이 아니며, 문자열입니다. 그래서 당신이 그것을 서버에서 serialize하고 파일을 생성 한 다음 그 데이터를 서버에 삽입해야한다고 생각합니다. 그것과는 별도로, 당신은 cropit 함수로부터'imageData' 변수를 얻는 것처럼 보이지만 절대로 그것을 서버에 보내지 않습니다. https://www.google.co.uk/search?safe=active&ei=hxcPWvmkCMTXkwX4uK_YCg&q=cropit+export+and+upload+to+PHP&oq=cropit+export+and+upload+to+PHP&gs_l=psy-ab을 참조하십시오. 3 ... 4634.7540.0.7735.18.9.0.0.0.0.160.274.0j2.2 .... 0 ... 1.1.64.psy-ab.16.1.112 ... 0i22i30k1j0i22i10i30k1.0.Zx_uEsYUyuA – ADyson

+0

@ADyson 관심을 가져 주셔서 감사합니다. 이것 (https://stackoverflow.com/questions/35125836/how-to-export-image-from-cropit-to-php-for-upload)은 훌륭하지만 문제는 내가 충분히 JQuery와 AJAX를 알지 못한다는 것입니다. 이 모든 것들을 모으십시오. 네가 나 좀 도와 준다면 고맙겠다. 미리 감사드립니다! – Kardo

+0

@ADyson : 또한 어떻게 사용하는지 잘 모르겠습니다. (https://stackoverflow.com/questions/4545081/how-to-do-file-upload-using-jquery-serialization) – Kardo

답변

0

마침내 문제를 발견하고 해결했습니다!

AJAX에서 데이터를 전송할 때 data: 'data=' + imageData,을 사용하는 데 문제가있었습니다. 그것을 다음과 같이 변경했습니다 : data: {base64data : imageData}

$.ajax({ 
    url: 'index.php?route=common/filemanager/upload&user_token={{ user_token }}&directory={{ directory }}', 
    type: 'post', 
    dataType: 'json', 
    data: {base64data : imageData}, 
    ...