- 정보공유
[JQUERY] php 와 ajax 를 이용해서 파일 업로드 할때 대용량 파일을 업로드 하는 방법
1. 서버 설정
; 파일 업로드 크기 제한
upload_max_filesize = 100M
; POST 데이터의 최대 크기
post_max_size = 100M
; 최대 실행 시간 (초)
max_execution_time = 300
; 최대 입력 시간 (초)
max_input_time = 300
; 메모리 제한
memory_limit = 128M
2. 클라이언트 측 (AJAX 및 JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Large File Upload</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="upload.js"></script>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="uploadFile()">Upload</button>
</body>
</html>
JavaScript (upload.js)
function uploadFile() {
const fileInput = $('#fileInput')[0];
const file = fileInput.files[0];
const chunkSize = 1024 * 1024; // 1MB
const totalChunks = Math.ceil(file.size / chunkSize);
let currentChunk = 0;
function uploadChunk() {
const start = currentChunk * chunkSize;
const end = Math.min(start + chunkSize, file.size);
const chunk = file.slice(start, end);
const formData = new FormData();
formData.append('file', chunk);
formData.append('chunkNumber', currentChunk);
formData.append('totalChunks', totalChunks);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (response) {
currentChunk++;
if (currentChunk < totalChunks) {
uploadChunk();
} else {
console.log('Upload complete');
}
},
error: function () {
console.error('Upload failed');
}
});
}
uploadChunk();
}
3. 서버 측 (PHP)
<?php
$targetDir = "uploads";
if (!file_exists($targetDir)) {
mkdir($targetDir, 0777, true);
}
$chunkNumber = isset($_POST['chunkNumber']) ? intval($_POST['chunkNumber']) : 0;
$totalChunks = isset($_POST['totalChunks']) ? intval($_POST['totalChunks']) : 0;
if (isset($_FILES['file']['tmp_name'])) {
$filePath = $targetDir . DIRECTORY_SEPARATOR . $_FILES['file']['name'] . '.part' . $chunkNumber;
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
}
if ($chunkNumber == $totalChunks - 1) {
$finalFilePath = $targetDir . DIRECTORY_SEPARATOR . $_FILES['file']['name'];
$fp = fopen($finalFilePath, 'w');
for ($i = 0; $i < $totalChunks; $i++) {
$chunkPath = $targetDir . DIRECTORY_SEPARATOR . $_FILES['file']['name'] . '.part' . $i;
$chunk = fopen($chunkPath, 'r');
while ($line = fread($chunk, 1024)) {
fwrite($fp, $line);
}
fclose($chunk);
unlink($chunkPath);
}
fclose($fp);
echo json_encode(["status" => "success"]);
}
?>