파일 시스템 액세스 API는 웹 개발자에게 사용자의 로컬 파일과 직접 상호 작용할 수있는 강력한 도구를 제공하여 읽기 및 쓰기 액세스를 가능하게합니다. 이는 브라우저 프론트 엔드 내에서 고급 텍스트 편집기, IDE, 이미지 조작 도구 및 향상된 가져 오기/내보내기 기능을 포함하여 정교한 웹 애플리케이션을 구축 할 수있는 흥미로운 가능성을 열어줍니다. 이 API 사용을 시작하는 방법을 살펴 보겠습니다.
파일 시스템 액세스 API 사용의 중요한 측면은 보안입니다. 모든 API 호출은 안전한 컨텍스트 내에서 사용자 제스처에 의해 시작되어야합니다. 아래 예제에서 클릭 이벤트를 사용하겠습니다.
단일 파일을 읽는 것은 매우 간결합니다.
파일 핸들하자; document.querySelector ( ". pick-file"). onclick = async () => { [FileHandle] = Await Window.ShowOpenFilePicker (); const file = await fileHandle.getFile (); const content = await file.text (); 반환 내용; };
Assuming an HTML button with the class "pick-file", clicking this button triggers the file picker via window.showOpenFilePicker()
. The selected file's handle is stored in fileHandle
. 함수는 파일의 내용을 텍스트로 반환합니다.
The fileHandle
object provides properties like kind
(either "file" or "directory") and name
.
// console.log (FileHandle)의 출력 예제 FileSystemFileHandle {Kind : 'File', 이름 : 'data.txt'}
fileHandle.getFile()
retrieves file details (last modified timestamp, name, size, type), and file.text()
extracts the file's content.
To read multiple files, pass an options object to showOpenFilePicker()
:
파일 핸들하자; const 옵션 = {배수 : true}; document.querySelector ( ". pick-file"). onclick = async () => { FileHandles = Await Window.showoPenFilePicker (옵션); // 여러 파일을 처리하는 코드 (아래 참조) };
The multiple
property (default: false
) enables multiple file selection. 추가 옵션은 허용 가능한 파일 유형을 지정합니다. 예를 들어 JPEG 이미지 만 허용하려면 다음과 같습니다.
const 옵션 = { 유형 : [{설명 : "이미지", 수락 : { "image/jpeg": ".jpeg"}}], ExcludeAcceptalloption : true, };
여러 파일 처리 :
const allcontent = await promise.all ( filehandles.map (async (filehandle) => { const file = await fileHandle.getFile (); const content = await file.text (); 반환 내용; }) ); Console.log (AllContent);
새 파일을 작성하고 쓰는 것도 간단합니다.
document.querySelector ( ". Save-File"). OnClick = async () => { const 옵션 = { 유형 : [{설명 : "테스트 파일", 수락 : { "text/plain": [ ".txt"]}}], }; const 핸들 = Await Window.showsaveFilePicker (옵션); Const Writable = Await Handle.createWritable (); writable.write ( "Hello World"); writable.close ()를 기다립니다. 리턴 핸들; };
window.showSaveFilePicker()
opens the file save dialog. handle.createWritable()
creates a writable stream, writable.write()
writes data, and writable.close()
finalizes the write operation.
기존 파일을 수정하려면 :
파일 핸들하자; document.querySelector ( ". pick-file"). onclick = async () => { [FileHandle] = Await Window.ShowOpenFilePicker (); const file = await fileHandle.getFile (); const Writable = await filehandle.createWritable (); writable.write ( "이것은 새로운 줄입니다"); // 파일에 추가됩니다 writable.close ()를 기다립니다. };
이 예제는 텍스트를 추가합니다. 덮어 쓰려면 원하는 전체 컨텐츠를 작성하십시오.
파일 시스템 액세스 API는 디렉토리 목록 및 파일/디렉토리 삭제도 지원합니다.
document.querySelector ( ". read-dir"). onclick = async () => { const directoryHandle = Await Window.ShowDirectoryPicker (); 대기 중 (directoryHandle.Values ())의 const intration {) { Console.log (Entry.kind, Entry.Name); } };
window.showDirectoryPicker()
selects a directory, and the loop iterates through its entries.
파일 삭제 :
document.querySelector ( ". pick-file"). onclick = async () => { const [filehandle] = await Window.showOpenFilePicker (); AWAIT FILEHANDLE.REMOVE (); };
디렉토리 삭제 (재귀 적으로) :
document.querySelector ( ". pick-folder"). onclick = async () => { const directoryHandle = Await Window.ShowDirectoryPicker (); directoryHandle.removeEntry ( 'data', {recursive : true}); };
파일 시스템 액세스 API는 최신 브라우저에서 광범위한 지원을 즐기지 만 Caniuse.com에서 가장 최신 호환성 정보를 확인하십시오. A ponyfill like browser-fs-access
can address compatibility gaps.
이 향상된 설명은 파일 시스템 액세스 API에 대한보다 포괄적이고 구조화 된 안내서를 제공합니다. 자리 표시 자 링크를 관련 문서에 대한 실제 링크로 바꾸는 것을 잊지 마십시오.
위 내용은 파일 시스템 액세스 API를 시작합니다의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!