search
HomeWeb Front-endJS TutorialPerform file operations in the browser

Perform file operations in the browser

When developing WebApp, you may encounter file-related operations, such as uploading files to the server, downloading files to the local, caching files, etc. The following will introduce several different ways to process files. operate.

Tag-based upload and download

The most common way to upload files is to use the input tag. By setting the input tag’s type="file", you can allow users to select files locally for upload.

function InputFile() {
    const [file, setFile] = useState<file null>(null);
    const handleChange = (e: React.ChangeEvent<htmlinputelement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setFile(file);
  };
    return <input onchange="{handleChange}" type="file">
}
</htmlinputelement></file>

File access API

File System Access API (File System Access API) is part of the file system API. Files can be read and written under the user's operation by using the API.

The following interfaces will be used when using this API for file operations

  • showOpenFilePicker: used to display a file picker and allow the user to select one or more files, and then return handles to these files;
export function PickerFS() {
    const [file, setFile] = useState<file null>(null);
    const handleChooseFile = async () => {
    const fileHandles = await window.showOpenFilePicker();
    const file = await fileHandles[0].getFile();
    setFile(file);
  };
  return <button onclick="{handleChooseFile}">Click</button>
}
</file>
  • showSaveFilePicker: used to display a file picker and allow the user to save a file (overwrite or create a new one);
export function PickerFS() {
    const handleChooseFile = async () => {
    const directoryHandle = await window.showDirectoryPicker();
    const keys = directoryHandle.keys();
    // 打印该目录下所有文件的名字
    for await (const key of keys) {
      console.log(key);
    }
  };
  return <button onclick="{handleChooseFile}">Click</button>
}
  • showDirectoryPicker: used to display a directory selector and allow the user to select a directory;
export function PickerFS() {
    const [file, setFile] = useState<file null>(null);
    const handleDownloadFile= async () => {
    const opts = {
      suggestedName: "test.txt",
      types: [
        {
          description: "Text file",
          accept: { "text/plain": [".txt"] },
        },
      ],
    };

    const fileHandle = await window.showSaveFilePicker(opts);
    const writable = await fileHandle.createWritable();
    await writable.write("Hello, world!");
    await writable.close();
  };
  return <button onclick="{handleDownloadFile}">Click</button>
}
</file>

Source Private File System

The source private file system is similar to the file access system above, both are part of the file system API, but the most direct difference between them is whether they are visible to users. The showXXX interfaces all need to open the file (directory) selector, and the user needs to actively select the file (directory). The saved file also needs to be saved to the path specified by the user, but the interaction of the source private file system will not be visible to the user, and the saved file The files are processed data and the original data cannot be seen by the user.

export function OpFs() {
  const handleChooseFile = async (event: React.ChangeEvent<htmlinputelement>) => {
    const fileList = event.target.files;
    const file = fileList && fileList[0];
    if (!file) return;

    const opfsRoot = await navigator.storage.getDi rectory();
    const fileHandle = await opfsRoot.getFileHandle(file.name, { create: true });
    const writable = await fileHandle.createWritable();
    await writable.write(file);
    await writable.close();
  };

  return <inputfile onchange="{handleChooseFile}"></inputfile>;
}
</htmlinputelement>

await navigator.storage.getDirectory() returns a file handle representing the root directory of the user's local file system, and then obtains the handle of the specified file through getFileHandle. create is true, which means that if the file does not exist, it will create one, and then use createWritable Create a writable stream. Developers can write data to the specified file through this writable stream, and finally close the writable stream.

Things to note

? The file access system is very similar to the source file system in use. Access to specific files or directories requires a file handle (FileSystemFileHandle) or a folder handle (FileSystemDirectoryHandle).

The handle can be understood as the packaging of the file itself, and the file is read (getFile) and written (createWritable) through the interface of the handle.

See

  • https://web.dev/articles/origin-private-file-system?hl=zh-cn#specifics_of_the_origin_private_file_system
  • https://developer.chrome.com/docs/capabilities/web-apis/file-system-access?hl=zh-cn
  • https://gine.me/posts/70f8e931bc17426fb54127948bcf4a0e
  • https://hughfenghen.github.io/posts/2024/03/14/web-storage-and-opfs/

The above is the detailed content of Perform file operations in the browser. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment