[javascript] 자바스크립트로 파일 업로드 및 다운로드 중 파일 해시 체크하기

파일을 업로드하고 다운로드하며 파일 해시를 ​​체크하기 위한 자바스크립트 기반의 솔루션을 살펴보겠습니다.

파일 업로드

우선 파일을 업로드하기 위해 파일 선택 input을 사용하고 선택된 파일을 가져오는 방법을 살펴보겠습니다.

// HTML 파일 내의 input 요소
<input type="file" id="fileInput">

// 자바스크립트로 파일 가져오기
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', (event) => {
  const file = event.target.files[0];
  console.log('선택된 파일:', file);
});

파일 다운로드

파일을 다운로드하기 위해서는 URL.createObjectURL을 사용하여 Blob 객체를 생성하고 다운로드 링크를 만들어야 합니다.

// 파일 다운로드
const downloadButton = document.getElementById('downloadButton');
const file = new Blob(['파일 내용'], { type: 'text/plain' });
downloadButton.href = URL.createObjectURL(file);
downloadButton.download = '파일.txt';

파일 해시 체크

파일의 해시를 체크하기 위해 SubtleCrypto API를 사용할 수 있습니다.

// 파일 해시 체크
async function calculateFileHash(file) {
  const buffer = await file.arrayBuffer();
  const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
  console.log('파일 해시:', hashHex);
}

위 코드를 사용하여 파일 업로드, 다운로드 및 파일 해시를 ​​체크하는 방법에 대해 알아보았습니다. 자바스크립트를 사용하여 이러한 작업을 수행할 수 있으며, 웹 앱에서 파일 관련 작업을 간편하게 수행할 수 있습니다.

이는 웹 앱 개발에서 유용한 기능이며, 사용자가 파일을 업로드하고 관리할 때 유용할 수 있습니다.