HTML Input File Value 변경

yuije·2022년 7월 26일
0

HTML에서 Input type file에 파일을 업로드 한 이후, 수정을 하려면 별도의 과정이 필요하다. (특히나 multiple 인 경우)

input의 파일을 업로드 하는 경우 input tag의 files에 file들이 채워지게 되는데, 이때 files는 배열이 아니므로 map이나 filter등의 array 관련 메소드들이 없다.

따라서 제거된 파일의 목록을 별도로 만들고 그 목록을 FileList 형태로 만들어서 재할당 해주는 방식이 필요하다.

const input = document.getElementById('file');


const filteredFileList = attachedfileList.filter((item) => item !== file);
// 1. 이전의 파일 목록 상태에서 제거할 파일을 필터링

const newFileList = new DataTransfer();
// 2. DataTransfer 인스턴스 생성

filteredFileList.map((item) => newFileList.items.add(item));
// 3. 인스턴스에 수정된 파일 목록을 할당

document.getElementById('assignment-file').files = newFileList.files;
// 4. 설정한 인스턴스의 files를 input files에 재할당
profile
Someday, I will.

0개의 댓글