파일 시스템 액세스 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

예, YoushouldLearnbothflexBoxAndgrid.1) FlexBoxisIdealforone-Dimensional, FlexiblelayoutSlikenavigationMenus.2) GridexCelsIntwo-Dimensional, ComplexDesignsSuchasmagazinElayouts.3) 결합 된 BothenSlayoutFlexibility 및 HeartingFortructur

자신의 코드를 리팩터링하는 것은 어떤 모습입니까? John Rhea는 자신이 쓴 오래된 CSS 애니메이션을 선택하고 최적화하는 사고 과정을 살펴 봅니다.

cssanimationsarenherinly에 hardbutreepracticenderstandingofcsspropertiesandtimingflestions.1) startsimpleants withsimpleatslikeScalingabuttononHoverusingKeyframes.2) useAsingfuctionslikecubic-bezierfornateffects, 그러한 분위기, 3)

@keyframesispopularduetoitstativerstatility 및 powerincreatingsmoothcssanimations.keytricksinclude : 1) states 사이에 moothtransitionsbettites, 2) 애니메이션 multiplepropertiessimultory, 3) vendorPixesforBrowsercompatibility, 4) 빗질을 사용하여

csScounterSearedTomanageAutomaticNumberingInberingInwebDesigns.1) 1) theCanbeusedfortablestoffContents, ListItems 및 CustomNumbering.2) AdvancedUsesInSinestedNumberingsystems.3) CreativeUseNvolvecust를 CreativeSinvolecust.4) CreativeSinvolvecust

특히 모바일 장치에 스크롤 그림자를 사용하는 것은 Chris가 이전에 다룬 미묘한 UX입니다. Geoff는 애니메이션 타임 라인 속성을 사용하는 새로운 접근 방식을 다루었습니다. 또 다른 방법이 있습니다.

빠른 새로 고침을 통해 실행합시다. 이미지 맵은 html 3.2로 돌아가는데, 먼저 서버 측 맵과 클라이언트 측지 맵은 맵 및 영역 요소를 사용하여 이미지를 통해 클릭 가능한 영역을 정의했습니다.

Devs State Survey는 이제 참여에 개방되어 있으며, 이전 설문 조사와 달리 코드, 직장, 건강, 취미 등을 제외한 모든 것을 포함합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전