Как сохранить файл

Оптимизируйте свои подборки Сохраняйте и классифицируйте контент в соответствии со своими настройками.

Thomas Steiner

Работа с файлами — одна из наиболее распространенных операций для приложений в Интернете. Традиционно пользователям приходилось загружать файл, вносить в него некоторые изменения, а затем загружать его снова, в результате чего копия оказывалась в папке «Загрузки». С помощью API доступа к файловой системе пользователи теперь могут напрямую открывать файлы, вносить изменения и сохранять изменения в исходном файле.

Современный способ

Использование метода showSaveFilePicker() API доступа к файловой системе.

Чтобы сохранить файл, вызовите showSaveFilePicker() , который возвращает обещание с FileSystemFileHandle . Вы можете передать желаемое имя файла в метод как < suggestedName: 'example.txt' >.

Классический способ

Использование элемента

Элемент на странице позволяет пользователю щелкнуть по нему и загрузить файл. Хитрость теперь состоит в том, чтобы незаметно вставить элемент на страницу с помощью JavaScript и программно щелкнуть по нему.

Прогрессивное улучшение

Приведенный ниже метод использует API доступа к файловой системе, если он поддерживается, а в противном случае возвращается к классическому подходу. В обоих случаях функция сохраняет файл, но в случае поддержки API доступа к файловой системе пользователь получит диалоговое окно сохранения файла, в котором он может выбрать, где файл следует сохранить.

const saveFile = async (blob, suggestedName) => < // Feature detection. The API needs to be supported // and the app not run in an iframe. const supportsFileSystemAccess = 'showSaveFilePicker' in window && (() => < try < return window.self === window.top; >catch < return false; >>)(); // If the File System Access API is supported… if (supportsFileSystemAccess) < try < // Show the file save dialog. const handle = await showSaveFilePicker(< suggestedName, >); // Write the blob to the file. const writable = await handle.createWritable(); await writable.write(blob); await writable.close(); return; > catch (err) < // Fail silently if the user has simply canceled the dialog. if (err.name !== 'AbortError') < console.error(err.name, err.message); return; >> > // Fallback if the File System Access API is not supported… // Create the blob URL. const blobURL = URL.createObjectURL(blob); // Create the `` element and append it invisibly. const a = document.createElement('a'); a.href = blobURL; a.download = suggestedName; a.style.display = 'none'; document.body.append(a); // Programmatically click the element. a.click(); // Revoke the blob URL and remove the element. setTimeout(() => < URL.revokeObjectURL(blobURL); a.remove(); >, 1000); >; 

дальнейшее чтение

Демо

HTML

     🎉" /> How to save a file  

How to save a file

CSS

 :root < color-scheme: dark light; >html < box-sizing: border-box; >*, *:before, *:after < box-sizing: inherit; >body < margin: 1rem; font-family: system-ui, sans-serif; >img < max-width: 320px; height: auto; >label, button, textarea, input, img

JS

 const textarea = document.querySelector('textarea'); const textInput = document.querySelector('input.text'); const textButton = document.querySelector('button.text'); const img = document.querySelector('img'); const imgInput = document.querySelector('input.img'); const imgButton = document.querySelector('button.img'); const saveFile = async (blob, suggestedName) => < // Feature detection. The API needs to be supported // and the app not run in an iframe. const supportsFileSystemAccess = 'showSaveFilePicker' in window && (() => < try < return window.self === window.top; >catch < return false; >>)(); // If the File System Access API is supported… if (supportsFileSystemAccess) < try < // Show the file save dialog. const handle = await showSaveFilePicker(< suggestedName, >); // Write the blob to the file. const writable = await handle.createWritable(); await writable.write(blob); await writable.close(); return; > catch (err) < // Fail silently if the user has simply canceled the dialog. if (err.name !== 'AbortError') < console.error(err.name, err.message); return; >> > // Fallback if the File System Access API is not supported… // Create the blob URL. const blobURL = URL.createObjectURL(blob); // Create the `` element and append it invisibly. const a = document.createElement('a'); a.href = blobURL; a.download = suggestedName; a.style.display = 'none'; document.body.append(a); // Click the element. a.click(); // Revoke the blob URL and remove the element. setTimeout(() => < URL.revokeObjectURL(blobURL); a.remove(); >, 1000); >; textButton.addEventListener('click', async () => < const blob = new Blob([textarea.value], < type: 'text/plain' >); await saveFile(blob, textInput.value); >); imgButton.addEventListener('click', async () => < const blob = await fetch(img.src).then((response) =>response.blob()); await saveFile(blob, imgInput.value); >); 

Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons "С указанием авторства 4.0", а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.

Последнее обновление: 2024-03-13 UTC.