[javascript] 자바스크립트로 파일 업로드 및 다운로드 중 파일 속성 변경하기
파일을 웹 애플리케이션에 업로드하거나 사용자가 파일을 다운로드하도록 허용하는 과정에서 파일 속성을 변경해야 할 때가 있습니다. 자바스크립트를 사용하여 이러한 파일 속성을 쉽게 변경할 수 있습니다. 이 글에서는 자바스크립트로 파일을 업로드하고 다운로드하는 방법과 함께 파일 속성을 변경하는 방법을 알아보겠습니다.
파일 업로드
사용자가 파일을 업로드하려고 할 때, <input type="file">
요소를 사용하여 파일 선택 창을 생성합니다.
<input type="file" id="fileInput">
<button onclick="uploadFile()">Upload</button>
자바스크립트에서는 FileReader
객체를 사용하여 파일을 읽고 처리할 수 있습니다. 아래 코드는 파일을 선택했을 때 파일을 읽고 콘솔에 파일 이름을 출력하는 예제입니다.
function uploadFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function(event) {
console.log('Uploaded file:', file.name);
}
reader.readAsDataURL(file);
}
파일 다운로드
파일을 다운로드하려면, 파일의 URL을 생성하고 이를 사용자에게 제공해야 합니다. 아래는 자바스크립트로 파일 다운로드 링크를 생성하는 예제입니다.
function downloadFile() {
const fileUrl = 'https://example.com/file.zip';
const downloadLink = document.createElement('a');
downloadLink.href = fileUrl;
downloadLink.download = 'file.zip';
downloadLink.click();
}
파일 속성 변경
파일을 업로드하거나 다운로드하기 전에 파일의 속성을 변경해야 할 때가 있습니다. 예를 들어, 파일 이름을 바꾸거나 MIME 유형을 변경해야 할 수 있습니다. 아래는 파일 속성을 변경하는 방법의 예제입니다.
function changeFileProperties() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
// 파일 이름 변경
file.name = 'newFileName.txt';
// MIME 유형 변경
file.type = 'text/plain';
console.log('Changed file properties:', file);
}
결론
자바스크립트를 사용하여 파일 업로드 및 다운로드 중 파일 속성을 변경하는 방법에 대해 살펴보았습니다. 이러한 기술을 응용하여 파일 처리 기능을 더욱 강화하고 사용자 경험을 향상시킬 수 있습니다.
자세한 내용은 MDN Web Docs를 참고하시기 바랍니다.