위토즈 - 개발자프로그램판매공간

정보공유

[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"]);
}
?>








정보공유
Total 440건 1 페이지
번호 제목 글쓴이 날짜 조회
440 가장 심플한 예약 주문번호 생성 코드 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 05-28 439
열람중 php 와 ajax 를 이용해서 파일 업로드 할때 대용량 파일을 업로드 하는 방법 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 05-23 555
438 dl dt dd css 샘플 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 05-13 471
437 datepicker 를 이용해서 달력3개를 표시하고 원하는 날짜만 선택이 가능하도록. 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 04-28 721
436 입금된 주문도 준비, 배송전까지는 취소할 수 있도록 하는 방법 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 03-10 1203
435 CSS를 사용하여 4x4 형태의 갤러리 디자인 그리드 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 03-05 972
434 magnificPopup css 를 추가하여 popup 마다 다른 사이즈 로 띄우기. 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 01-16 1502
433 magnificPopup 조건이 맞지 않으면 popup 띄우지 않기. 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 01-12 1460
432 magnificPopup iframe 으로 form submit 하기 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 01-12 1567
431 mysql 사용자 함수 생성 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 01-09 1346
430 html 로 된 svg 태그를 png 파일로 만들기. 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 01-08 1601
429 prepare bind_param 쿼리구분 select * 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 08-14 2136
428 javascript 플랫폼 디바이스 확인 함수 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 07-13 2290
427 stmt 등록 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 06-14 2678
426 prepare 함수 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 05-16 2494