[javascript] 자바스크립트로 파일 다운로드 진행상황 표시하기

파일을 다운로드할 때 사용자에게 진행 상황을 시각적으로 보여주는 것은 사용성을 향상시키는 데 도움이 됩니다. 이를 위해 HTML, CSS 및 JavaScript를 이용하여 간단한 파일 다운로드 진행상황 표시 기능을 구현해봅시다.

HTML 및 CSS 설정

가장 먼저 HTML과 CSS를 이용하여 다운로드 진행 상황을 표시할 요소를 생성합니다.

<!-- index.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <button id="downloadButton">파일 다운로드</button>
  <progress value="0" max="100" id="progressBar"></progress>
  <span id="progressText">0%</span>
  <script src="script.js"></script>
</body>
</html>
/* styles.css */
#progressBar {
  display: none;
}

JavaScript로 파일 다운로드 및 진행 상황 표시

이제 JavaScript를 사용하여 파일을 다운로드하고 다운로드 진행 상황을 표시해봅시다.

// script.js
const downloadButton = document.getElementById('downloadButton');
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');

downloadButton.addEventListener('click', () => {
  // 파일 다운로드 URL
  const fileUrl = 'your_file_url_here';

  // 파일 다운로드 및 진행 상황 표시
  fetch(fileUrl).then(response => {
    const contentLength = response.headers.get('content-length');
    progressBar.max = contentLength;
    response.body
      .getReader()
      .read()
      .then(function processResult({ done, value }) {
        if (done) {
          progressText.textContent = '다운로드 완료';
          return;
        }

        downloaded += value.length;
        progressBar.value = downloaded;
        progressText.textContent = `${Math.round((downloaded / contentLength) * 100)}%`;

        // 다음 청크를 읽음
        return reader.read().then(processResult);
      });
  });
  progressBar.style.display = 'block'; // 다운로드 바 표시
});

위의 코드는 사용자가 다운로드 버튼을 클릭하면 fetch API를 사용하여 파일을 받아오고, 받아온 파일의 크기를 이용하여 진행 상황을 계산하여 표시합니다. 마지막으로 받아온 파일의 크기를 이용하여 진행 상황을 계산하고, 이를 progressBarprogressText에 표시하게 됩니다.

이제 위의 코드를 사용하여 파일 다운로드 진행상황을 시각적으로 표시할 수 있게 됩니다.

이것은 기본적인 예시에 불과하며, 더 많은 기능 및 개선사항이 필요할 수 있습니다. 완성도를 높이기 위해선 더 많은 테스트와 보완이 필요합니다.