[javascript] 자바스크립트로 파일 업로드 및 다운로드 중 파일 압축 기능 추가하기

파일 업로드 및 다운로드 기능은 웹 애플리케이션에서 자주 사용되며, 자바스크립트를 사용하여 이러한 기능을 더 확장할 수 있습니다. 이 글에서는 파일을 업로드하고 다운로드하는 기능에 파일 압축 기능을 추가하는 방법을 알아보겠습니다.

1. 파일 업로드

HTML <input type="file"> 요소를 사용하여 파일을 선택하고, 선택한 파일을 서버에 업로드합니다.

<input type="file" id="fileInput">
<button onclick="uploadFile()">업로드</button>
function uploadFile() {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];
  
  const formData = new FormData();
  formData.append('file', file);
  
  // 서버에 파일 업로드 요청
  fetch('/upload', {
    method: 'POST',
    body: formData
  });
}

2. 파일 다운로드

서버에서 파일을 다운로드 받아 사용자에게 제공할 때, 자바스크립트를 사용하여 이를 처리할 수 있습니다.

function downloadFile() {
  fetch('/download', {
    method: 'GET'
  })
  .then(response => response.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'file.zip';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
  });
}

3. 파일 압축

파일을 클라이언트 측에서 압축하여 다운로드할 수도 있습니다. JSZip과 같은 라이브러리를 사용하여 파일을 압축할 수 있습니다.

function compressAndDownload() {
  const zip = new JSZip();
  const file1 = '내용1';
  const file2 = '내용2';
  zip.file('file1.txt', file1);
  zip.file('file2.txt', file2);
  
  zip.generateAsync({type:"blob"})
  .then(function(content) {
    const url = window.URL.createObjectURL(content);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'compressedFiles.zip';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
  });
}

이제 자바스크립트를 사용하여 파일 업로드, 다운로드 및 파일 압축 기능을 추가하는 방법에 대해 간략하게 알아보았습니다. 이러한 기능을 적절히 활용하면 사용자가 파일을 보다 쉽게 관리하고 공유할 수 있게 될 것입니다.