html javascript 대용량 파일 업로드 구현
분할방식의 업로드 샘플코드입니다.
서버의 업로드 1회 업로드 용량 제한에도 대응하는 코드로,
디테일을 구현하면 이어 올리기 등 또한 구현 가능합니다.
필요하신분들 참고하세요.
눈으로만 검수한 코드라 디버깅이 필요할 수 있습니다.
php
[code]
<?php
// 파일 업로드 처리
if (isset($_FILES['file'])) {
$file = $_FILES['file'];
// 파일 크기
$fileSize = $file['size'];
// 분할 크기 (예: 10MB)
$chunkSize = 10 * 1024 * 1024;
// 분할된 청크 수
$numChunks = ceil($fileSize / $chunkSize);
// 임시 디렉토리 생성
$tempDir = sys_get_temp_dir() . '/file-upload';
if (!file_exists($tempDir)) {
mkdir($tempDir, 0777, true);
}
// 파일 분할
for ($i = 0; $i < $numChunks; $i++) {
// 분할된 청크 시작 바이트
$startByte = $i * $chunkSize;
// 분할된 청크 끝 바이트
$endByte = min($fileSize, $startByte + $chunkSize - 1);
// 분할된 청크 읽기
$chunk = fopen($file['tmp_name'], 'rb');
fseek($chunk, $startByte);
$chunkData = fread($chunk, $chunkSize);
fclose($chunk);
// 분할된 청크 저장
$chunkFile = fopen($tempDir . '/chunk-' . $i, 'wb');
fwrite($chunkFile, $chunkData);
fclose($chunkFile);
}
// 분할된 청크 정보 저장
$chunkInfo = array();
for ($i = 0; $i < $numChunks; $i++) {
$chunkInfo[] = array(
'name' => 'chunk-' . $i,
'size' => filesize($tempDir . '/chunk-' . $i)
);
}
// 분할된 청크 정보 JSON으로 출력
echo json_encode($chunkInfo);
}
[/code]
html & javascript
[code]
<script>
const form = document.getElementById('file-upload-form');
const progressBar = document.getElementById('progress-bar');
// 파일 선택 이벤트
form.addEventListener('change', (event) => {
// 업로드할 파일 가져오기
const file = event.target.files[0];
// 파일 크기
const fileSize = file.size;
// 분할 크기 (예: 10MB)
const chunkSize = 10 * 1024 * 1024;
// 분할된 청크 수
const numChunks = Math.ceil(fileSize / chunkSize);
//코드 일부 삭제
// 파일 분할
for (let i = 0; i < numChunks; i++) {
// 분할된 청크 시작 바이트
const startByte = i * chunkSize;
// 분할된 청크 끝 바이트
const endByte = Math.min(fileSize, startByte + chunkSize - 1);
// 분할된 청크 읽기
const chunk = file.slice(startByte, endByte + 1);
// 분할된 청크 저장
const chunkFile = new File([chunk], 'chunk-' + i, {
type: file.type
});
// 분할된 청크 업로드
uploadFile(chunkFile);
}
});
// 파일 업로드 함수
function uploadFile(file) {
// FormData 객체 생성
const formData = new FormData();
// 파일 추가
formData.append('file', file);
// AJAX 요청 생성
const xhr = new XMLHttpRequest();
// 업로드 진행 이벤트
xhr.upload.addEventListener('progress', (event) => {
// 업로드 진행률 계산
const progress = (event.loaded / event.total) * 100;
// 진행률 표시줄 업데이트
progressBar.style.width = `${progress}%`;
});
// 서버 응답 이벤트
xhr.addEventListener('load', (event) => {
// 업로드 상태 가져오기
const status = JSON.parse(event.target.response);
// 업로드 상태 표시
console.log(`파일: ${status.name}, 크기: ${status.size}, 상태: ${status.status}`);
});
// 요청 보내기
xhr.open('POST', 'upload.php');
xhr.send(formData);
}
</script>
<form id="file-upload-form"></form>
<input type="file">
<button type="submit">업로드</button>
</form>
<div id="progress-bar"></div>
[/code]
댓글 9개
공유 감사합니다!
아직은 적용할만한 곳은 없지만 쓸 기회가 생긴다면 공유해주신 코드를 참고해서 작업해볼게요!
수고하셨습니다 ^^
자바스크립트에서 필요없는 코드 같습니다.
// 임시 디렉토리 생성
const tempDir = sys_get_temp_dir() + '/file-upload';
if (!file_exists(tempDir)) {
mkdir(tempDir, 0777, true);
}
@티로그 그렇겠네요. 수정하였습니다.
감사합니다 ^^
감사합니다
오... 좋은 정보 감사합니다.
감사합니다.
게시판 목록
영카트5 팁자료실
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|
| 401 |
|
1년 전 | 2333 | |
| 400 |
|
1년 전 | 1385 | |
| 399 | 1년 전 | 2770 | ||
| 398 | 1년 전 | 866 | ||
| 397 |
|
1년 전 | 2745 | |
| 396 | 1년 전 | 1336 | ||
| 395 | 1년 전 | 734 | ||
| 394 | 1년 전 | 451 | ||
| 393 | 1년 전 | 1010 | ||
| 392 |
다케미카코
|
1년 전 | 2651 | |
| 391 |
|
1년 전 | 804 | |
| 390 |
사노라가노라
|
1년 전 | 1050 | |
| 389 | 1년 전 | 503 | ||
| 388 |
|
1년 전 | 85436 | |
| 387 | 1년 전 | 822 | ||
| 386 | 1년 전 | 2519 | ||
| 385 | 1년 전 | 828 | ||
| 384 | 2년 전 | 1848 | ||
| 383 |
|
2년 전 | 1875 | |
| 382 | 2년 전 | 1427 | ||
| 381 | 2년 전 | 2578 | ||
| 380 |
|
2년 전 | 2128 | |
| 379 |
e4uhack
|
2년 전 | 2073 | |
| 378 |
|
2년 전 | 1066 | |
| 377 |
|
2년 전 | 1381 | |
| 376 | 2년 전 | 1211 | ||
| 375 |
|
2년 전 | 2234 | |
| 374 |
페이투페이
|
2년 전 | 1726 | |
| 373 |
|
2년 전 | 1454 | |
| 372 | 2년 전 | 1233 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기