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

정보공유

[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 52건 1 페이지
번호 제목 글쓴이 날짜 조회
52 금액 카운팅 모션 다라라락 변화 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 06-26 854
열람중 php 와 ajax 를 이용해서 파일 업로드 할때 대용량 파일을 업로드 하는 방법 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 05-23 1607
50 datepicker 를 이용해서 달력3개를 표시하고 원하는 날짜만 선택이 가능하도록. 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 04-28 1541
49 magnificPopup css 를 추가하여 popup 마다 다른 사이즈 로 띄우기. 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 01-16 2271
48 magnificPopup 조건이 맞지 않으면 popup 띄우지 않기. 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 01-12 2299
47 magnificPopup iframe 으로 form submit 하기 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 01-12 2349
46 magnificPopup 으로 창을 호출 후 날짜 입력박스에 datepicker 실행되지 않는경우 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 04-13 3215
45 magnificPopup 파라미터 변수 값 ajax 타입으로 전송 방법 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 03-31 3216
44 jquery 로 text 필드와 file 첨부를 동시에. 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 03-09 3282
43 파일 첨부 를 이미지버튼으로 대체한경우 첨부한 파일명 표시하기. 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 03-09 3234
42 폼을 생성하고 선택된(필요한) 영역의 값만 전송 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 01-17 3886
41 탭으로 나눠지는 슬라이드 쇼 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 11-13 4913
40 jquery fullcalendar eventOrder 정렬 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 08-23 13476
39 주소복사 계좌번호복사 URL복사 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 05-11 12287
38 jquery 스와이프 메뉴 위토즈쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 04-15 13124