본문 바로가기

개발/Web

PHP CI Chunk File Upload - Plupload

업무 중 IIS 웹 서버에 대량 파일 업로드를 개발하게 되어 과정을 기록한다.

영상 업로드를 위해 10GB 이상의 파일을 웹 서버에 부하를 최소한으로 주며 업로드할 필요가 있었다.

방법을 찾던 중 Chunk 방식의 분할 파일 업로드를 확인했다.

PHP지원 라이브러리 중 Plupload 가 괜찮아 보여서 사용하게 되었다.

(처음에는 UI 보고 선택했다.)

[프론트]

<ul id="filelist"></ul> <!-- Browse 한 파일의 목록을 html로 찍어주는 부분 -->
<br />
 
<div id="container">
    <!-- href="javascript"로 링크가 아닌 자바스크립트로 동작하게 한다. -->
    <a id="browse" href="javascript:;">[Browse...]</a> 
    <!-- Browse : 탐색기를 통한 업로드 할 파일을 선택 -->
    <a id="start-upload" href="javascript:;">[Start Upload]</a>
    <!-- Upload : 선택한 업로드 할 파일을 url로 전송, 비동기 방식 -->
</div>
 
<br />
<pre id="console"></pre>
<!-- Error Handling, 에러 내용 해당 부분에 출력 및 디버깅 -->
 
<script type="text/javascript">
 
var uploader = new plupload.Uploader({ // plupload 라이브러리의 Uploader 객체 생성
  browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
  url: 'YOUR_DATA_TARGET_DIRECTORY', // data 를 전송할 url
  chunk_size: '10mb', // chunk 로 분할 전송할 사이즈
  max_file_size: '50gb', // Uploader 을 통해 전송 가능한 파일의 최대 사이즈, over시 error return
  max_retries: 3, // chunk 분할 전송 중 실패 시 재전송 시도 횟수
});
 
uploader.bind('FilesAdded', function(up, files) { // file을 browse 로 추가했을때 발생 이벤트
  var html = ''; 
  plupload.each(files, function(file) { // plupload 라이브러리 내 files을 배열로 돌린다.
    html += '<li id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') 
<b></b></li>'; // result : <li id="FILEID">"FILE_NAME_TEXT" ("FILE_SIZE") <b>PROGRESS</b></li>
  });
  document.getElementById('filelist').innerHTML += html;
  // id가 filelist 인 객체에 html형식으로 html 변수의 내용을 입력
});
uploader.bind('UploadProgress', function(up, file) { // file upload 진행중 이벤트
  document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + 
file.percent + "%</span>"; 
// id 가 변수 file.id 인 객체 중 tagname이 b인 최초의 객체에 html 형식으로 내용을 입력
// result : <span>"FILE.PERCENT"%</SPAN>
});
// uploader.bind('ChunkUploaded', function(up, file, info) { // 청크 업로드 완료시 이벤트
    // console.log(info);
// })
uploader.bind('Error', function(up, err) { // Uploader error 발생 이벤트
  document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
// id가 console인 객체에 html 형식으로 내용 입력
// result : Error # 200 HTTP ERROR
});
document.getElementById('start-upload').onclick = function() { 
//id가 start-upload인 객체 클릭 시 동적 함수 바인딩
  uploader.start();
//uploader 객체 실행
};
uploader.bind('FileUploaded', function(up, file, response) { 
// 파일 업로드 완료 시 이벤트
    var data = $.parseJSON(response.response);
// 응답되는 데이터를 data 변수에 저장
    // Use your object, eg data.Message
    console.log(data);
// 응답 내용을 console 에 출력
});
uploader.init();
// uploader 인스턴스 초기화 및 이벤트 리스너 적용
 
</script>

[백엔드]

}

function upload_video_process() {
// Make sure file is not cached (as it happens for example on iOS devices)
// HTTP Request Header 세팅
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 * 600);
// Uncomment this one to fake upload time
// usleep(5000);
// Settings
$targetDir = "C:" . DIRECTORY_SEPARATOR . "FOLDERNAME";
// echo $targetDir;
//$targetDir = '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 (isset($_REQUEST["name"])) {
    $fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
    $fileName = $_FILES["file"]["name"];
} else {
    $fileName = uniqid("file_");
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
// echo $filePath;
// 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 && is_dir($targetDir) && ($dir = opendir($targetDir))) {
    while (($file = readdir($dir)) !== false) {
        $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
        // 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) 
&& ($tmpfilePath != "{$filePath}.part")) {
            @unlink($tmpfilePath);
        }
    }
    closedir($dir);
} else
    die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory
."}, "id" : "id"}');
// Open temp file
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
    die('{"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"])) {
        die('{"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")) {
        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input 
stream."}, "id" : "id"}');
    }
} else {    
    if (!$in = @fopen("php://input", "rb")) {
        die('{"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);
}
// Return Success JSON-RPC response
die('{"jsonrpc" : "2.0", "result" : upload-success, "id" : "id"}');
        $this->load->view('/header',$this->header);
        $this->load->view('/music/upload_video', $r_data);
        $this->load->view('/footer');
    }
반응형

'개발 > Web' 카테고리의 다른 글

TypeScript 정적 타이핑  (0) 2020.06.21
TypeScript 환경구축  (0) 2020.06.20
[Node.js] 프레임워크 Express, Koa, Hapi  (0) 2020.06.05
Node.js 서버 띄우기  (0) 2020.06.05
Node.js 소개 및 설치  (0) 2020.06.05