如何保存文件

Thomas Steiner
Thomas Steiner

处理文件是 Web 应用最常见的操作之一。过去,用户需要先上传文件,对文件进行一些更改,然后重新下载,因此会在“下载内容”文件夹中生成副本。借助 File System Access API,用户现在可以直接打开文件、进行修改,并将更改保存回原始文件。

现代风

使用 File System Access API 的 showSaveFilePicker() 方法

如需保存文件,请调用 showSaveFilePicker(),后者会返回带有 FileSystemFileHandle 的 promise。您可以将所需的文件名作为 { suggestedName: 'example.txt' } 传递给方法。

浏览器支持

  • 86
  • 86
  • x
  • x

来源

经典路线

使用 <a download> 元素

网页上的 <a download> 元素可让用户点击该元素并下载文件。现在,诀窍在于使用 JavaScript 以不可见方式将元素插入网页,然后以程序化方式点击元素。

浏览器支持

  • 15
  • 13
  • 20
  • 10.1

来源

渐进式增强

下面的方法会在支持 File System Access API 的情况下使用,否则会回退到传统方法。在这两种情况下,函数都会保存文件,但如果系统支持 File System Access 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 `<a download>` 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

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="icon"
      href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
    />
    <title>How to save a file</title>
  </head>
  <body>
    <h1>How to save a file</h1>

    <label
      >Text to save
      <textarea rows="3">
Some sample text for you to save. Feel free to edit this.</textarea
      >
    </label>
    <label>File name <input class="text" value="example.txt" /></label>
    <button class="text" type="button">Save text</button>

    <label
      >Image to save
      <img
        src="https://cdn.glitch.global/75170424-3d76-41d7-ae77-72d0efb0401b/AVIF%20Test%20picture%20(JPEG%20converted%20to%20AVIF%20with%20Convertio).avif?v=1658240752363"
        alt="Blue flower."
        width="630"
        height="420"
    /></label>
    <label>File name <input class="img" value="example.avif" /></label>
    <button class="img" type="button">Save image</button>
  </body>
</html>

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 {
  display: block;
  margin-block: 1rem;
}
        

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);
});
        

如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。

最后更新时间 (UTC):2023-10-25。