2017-11-02 5 views
0

저는 laravel에 새로 왔으며 이미지 업로드를 위해 내부에 업 로더를 통합하려고합니다.이미지 업로드 중 ERROR 419 (알 수없는 상태) 받기 Laravel 5.5

이미지를 업로드 할 때 알 수없는 상태 오류가 발생합니다. 여기

스크립트 내가보기 사용하고있다 :

public function upload_image() 
{ 
    if(! ini_get('date.timezone')) 
    { 
     date_default_timezone_set('GMT'); 
    } 
    // Make sure file is not cached (as it happens for example on iOS devices) 
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
    header("Cache-Control: no-store, no-cache, must-revalidate"); 
    header("Cache-Control: post-check=0, pre-check=0", false); 
    header("Pragma: no-cache"); 

    /* 
    // Support CORS 
    header("Access-Control-Allow-Origin: *"); 
    // other CORS headers if any... 
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { 
      exit; // finish preflight CORS requests here 
    } 
    */ 

    // 5 minutes execution time 
    @set_time_limit(5 * 60); 

    // Uncomment this one to fake upload time 
    // usleep(5000); 

    // Settings 
    $targetDir = base_path().'/uploads'; 
    $cleanupTargetDir = true; // Remove old files 
    $maxFileAge = 5 * 3600; // Temp file age in seconds 

    // Create target dir 
    if (!file_exists($targetDir)) { 
     @mkdir($targetDir); 
    } 
    //echo $targetDir; 
    // Get a file name 
    if (isset($_REQUEST["name"])) { 
      $fileName = $_REQUEST["name"]; 
    } elseif (!empty($_FILES)) { 
      $fileName = $_FILES["file"]["name"]; 
    } else { 
      $fileName = uniqid("file_"); 
    } 

    $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName; 

    // Chunking might be enabled 
    $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0; 
    $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0; 


    // Remove old temp files  
    if ($cleanupTargetDir) { 
     if (!is_dir($targetDir) || !$dir = opendir($targetDir)) { 
       $data = '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'; 
     } 

     while (($file = readdir($dir)) !== false) { 

       $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; 

       // If temp file is current file proceed to the next 
       if ($tmpfilePath == "{$filePath}.part") { 

         continue; 
       } 

       // Remove temp file if it is older than the max age and is not the current file 
       if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) { 
         @unlink($tmpfilePath); 
       } 
     } 
     closedir($dir); 
    } 


    // Open temp file 
    if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) { 
      $data = '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'; 
    } 
    if (!empty($_FILES)) { 
      if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) { 
        $data = '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'; 
      } 

      // Read binary input stream and append it to temp file 
      if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) { 
        $data = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'; 
      } 
    } else { 
      if (!$in = @fopen("php://input", "rb")) { 
        $data = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'; 
      } 
    } 

    while ($buff = fread($in, 4096)) { 
      fwrite($out, $buff); 
    } 

    @fclose($out); 
    @fclose($in); 

    // Check if file has been uploaded 
    if (!$chunks || $chunk == $chunks - 1) { 
      // Strip the temp .part suffix off 
      rename("{$filePath}.part", $filePath); 
    } 
    $data = '{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'; 
    return response()->json($data); 
    //return '{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'; 
} 

:

여기
Route::post('/image-upload', '[email protected]_image'); 

제어기의 upload_image 함수이다 : 여기

var uploader = new plupload.Uploader({ 
     runtimes : 'html5,flash,silverlight,html4', 
     browse_button : 'bg_upload', // you can pass an id... 
     container: document.getElementById('bg_container'), // ... or DOM Element itself 
     url : "{{ url('/') }}/image-upload?_token="+$('meta[name="csrf-token"]').attr('content'), 
     unique_names : false, 
     max_file_count: 1, 
     multi_selection: true, 
     flash_swf_url : "{{ URL::asset('admin/js/pluploader/Moxie.swf') }}", 
     silverlight_xap_url : "{{ URL::asset('admin/js/pluploader/Moxie.xap') }}", 
     filters : { 
      max_file_size : '60mb' 
     }, 
     init: { 
      FileUploaded: function (up, file) { 
       var upload_path = "{{ url('/uploads') }}"; 
       var img = jQuery('<img alt="click to change image" src="'+upload_path+file.name+'" style="width:auto; max-height:400px;">'); 
       jQuery("#bg_upload").html(img); 
      }, 
      FilesAdded: function(up, files) { 
       jQuery("#progress_file").css("display","block"); 
       plupload.each(files, function(file) { 
        var img_type = file.name; 
        jQuery("#progress_file").append('<div id="' + file.id + '" >' + img_type + ' (' + plupload.formatSize(file.size) + ')<b></b></div>'); 
       }); 
       uploader.start(); 
      }, 
      UploadProgress: function(up, file) { 
       jQuery("#"+file.id).find("b").html('<span>' + file.percent + "%</span>"); 
      }, 
      UploadComplete: function() { 
       jQuery("#progress_file").html(""); 
       jQuery("#progress_file").css("display","none"); 
      }, 
      Error: function(up, err) { 
       console.log("\nError #" + err.code + ": " + err.message); 
       //document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message)); 
      } 
     } 
    }); 
    uploader.init(); 

내가 정의 경로이고 아무도 내가 틀렸다고 말할 수 있습니까?

미리 감사드립니다.

+0

url에'?'ie.,'G ET'와'POST' 루트가 있습니다 –

+0

나는 똑같은 에러를 얻었습니다. –

+0

에러가 나타나지 않습니다 .. 캐시 문제라고 생각합니다. 나는 무슨 일이 일어나는 지 모르며 파일 업로드를 시작합니다. –

답변

0

코드가 작동하기 시작합니다. 캐시 문제일지도 모릅니다. 무슨 일이 일어나고 코드가 업로드되기 시작하는지 모르겠습니다. 컨트롤러

Route::post('/image-upload', '[email protected]_image'); 

이미지 업로드 코드 :

여기
var uploader = new plupload.Uploader({ 
     runtimes : 'html5,flash,silverlight,html4', 
     browse_button : 'bg_upload', // you can pass an id... 
     container: document.getElementById('bg_container'), // ... or DOM Element itself 
     url : "{{ url('/') }}/image-upload?_token="+$('meta[name="csrf-token"]').attr('content'), 
     unique_names : false, 
     max_file_count: 1, 
     multi_selection: false, 
     flash_swf_url : "{{ URL::asset('admin/js/pluploader/Moxie.swf') }}", 
     silverlight_xap_url : "{{ URL::asset('admin/js/pluploader/Moxie.xap') }}", 
     filters : { 
      max_file_size : '60mb' 
     }, 
     init: { 
      FileUploaded: function (up, file) { 
       var upload_path = "{{ URL::asset('uploads') }}"; 
       var img = jQuery('<img alt="click to change image" src="'+upload_path+"/"+file.name+'" style="width:100%;">'); 
       jQuery("#bg_container").addClass("no-border"); 
       jQuery("#bg_upload").html(img); 
      }, 
      FilesAdded: function(up, files) { 
       jQuery("#progress_file").css("display","block"); 
       plupload.each(files, function(file) { 
        var img_type = file.name; 
        jQuery("#progress_file").append('<div id="' + file.id + '" >' + img_type + ' (' + plupload.formatSize(file.size) + ')<b></b></div>'); 
       }); 
       uploader.start(); 
      }, 
      UploadProgress: function(up, file) { 
       jQuery("#"+file.id).find("b").html('<span>' + file.percent + "%</span>"); 
      }, 
      UploadComplete: function() { 
       jQuery("#progress_file").html(""); 
       jQuery("#progress_file").css("display","none"); 
      }, 
      Error: function(up, err) { 
       console.log("\nError #" + err.code + ": " + err.message); 
       //document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message)); 
      } 
     } 
    }); 
    uploader.init(); 

이 경로 코드입니다 : 내가보기에 사용하고

업 로더 스크립트 : 여기

내 마지막 코드
public function upload_image(Request $request) 
{ 
    if(! ini_get('date.timezone')) 
    { 
     date_default_timezone_set('GMT'); 
    } 
    // Make sure file is not cached (as it happens for example on iOS devices) 
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
    header("Cache-Control: no-store, no-cache, must-revalidate"); 
    header("Cache-Control: post-check=0, pre-check=0", false); 
    header("Pragma: no-cache"); 

    // 5 minutes execution time 
    @set_time_limit(5 * 60); 

    // Uncomment this one to fake upload time 
    // usleep(5000); 

    // Settings 
    $targetDir = public_path().'/uploads'; 
    $cleanupTargetDir = true; // Remove old files 
    $maxFileAge = 5 * 3600; // Temp file age in seconds 

    // Create target dir 
    if (!file_exists($targetDir)) { 
     @mkdir($targetDir); 
    } 
    // Get a file name 
    if ($request->input('name')) { 
      $fileName = $request->input('name'); 
    } elseif (!empty($_FILES)) { 
      $fileName = $request->image->getClientOriginalName(); 
    } else { 
      $fileName = uniqid("file_"); 
    } 

    $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName; 

    // Chunking might be enabled 
    $chunk = $request->input("chunk") ? intval($request->input("chunk")) : 0; 
    $chunks = $request->input("chunks") ? intval($request->input("chunks")) : 0; 


    // Remove old temp files  
    if ($cleanupTargetDir) { 
     if (!is_dir($targetDir) || !$dir = opendir($targetDir)) { 
       $data = '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'; 
     } 

     while (($file = readdir($dir)) !== false) { 

       $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; 

       // If temp file is current file proceed to the next 
       if ($tmpfilePath == "{$filePath}.part") { 

         continue; 
       } 

       // Remove temp file if it is older than the max age and is not the current file 
       if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) { 
         @unlink($tmpfilePath); 
       } 
     } 
     closedir($dir); 
    } 


    // Open temp file 
    if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) { 
      $data = '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'; 
    } 
    if (!empty($_FILES)) { 
      if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) { 
        $data = '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'; 
      } 

      // Read binary input stream and append it to temp file 
      if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) { 
        $data = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'; 
      } 
    } else { 
      if (!$in = @fopen("php://input", "rb")) { 
        $data = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'; 
      } 
    } 

    while ($buff = fread($in, 4096)) { 
      fwrite($out, $buff); 
    } 

    @fclose($out); 
    @fclose($in); 

    // Check if file has been uploaded 
    if (!$chunks || $chunk == $chunks - 1) { 
      // Strip the temp .part suffix off 
      rename("{$filePath}.part", $filePath); 
    } 
    $data = '{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'; 
    return response()->json($data); 
}