js、vue轻松访问资源管理器上传文件、保存文件、选择目录

 1.前言

前言: 最近遇到了一个小问题,就是右键列表点击导入按钮然后在资源管理器内选择文件导入数据,但是如果在右键列表内写一个<input type="file">有点麻烦,这时我们偶然发现了一个很好用的小东西那就是GitHub - GoogleChromeLabs/browser-fs-access: File System Access API with legacy fallback in the browser

 他不仅可以实现选择文件,还可以实现导出文件以及选择目录,完美契合需求

下面我们来使用它!!

2.安装

可以使用 npm 安装该模块。(看GitHub上只提供了这个)

npm install --save browser-fs-access

3.使用示例

该模块功能检测对文件系统访问 API 的支持,并且只加载实际相关的代码。

// 导入的方法将使用文件系统
// 访问API或回退实现。
import {
  fileOpen,
  directoryOpen,
  fileSave,
  supported,
} from 'https://unpkg.com/browser-fs-access';

(async () => {
  if (supported) {
    console.log('Using the File System Access API.');
  } else {
    console.log('Using the fallback implementation.');
  }

  // 打开一个文件。
  const blob = await fileOpen({
    mimeTypes: ['image/*'],
  });

  // 打开多个文件。
  const blobs = await fileOpen({
    mimeTypes: ['image/*'],
    multiple: true,
  });

  // 打开不同MIME类型的文件。
  const blobs = await fileOpen([
    {
      description: 'Image files',
      mimeTypes: ['image/jpg', 'image/png', 'image/gif', 'image/webp'],
      extensions: ['.jpg', '.jpeg', '.png', '.gif', '.webp'],
      multiple: true,
    },
    {
      description: 'Text files',
      mimeTypes: ['text/*'],
      extensions: ['.txt'],
    },
  ]);

  // 打开目录中的所有文件,
  // 递归地包括子目录。
  const blobsInDirectory = await directoryOpen({
    recursive: true,
  });

  // 保存一个文件
  await fileSave(blob, {
    fileName: 'Untitled.png',
    extensions: ['.png'],
  });

  // 保存将流式传输的“响应”。
  const response = await fetch('foo.png');
  await fileSave(response, {
    fileName: 'foo.png',
    extensions: ['.png'],
  });

  // 保存将流式传输的“Promise<Blob>”。
  // 无需“等待”要创建的“Blob”。
  const blob = createBlobAsyncWhichMightTakeLonger(someData);
  await fileSave(response, {
    fileName: 'Untitled.png',
    extensions: ['.png'],
  });
})();

4.API文档

(1)打开文件

// Options are optional. You can pass an array of options, too.
const options = {
  // List of allowed MIME types, defaults to `*/*`.
  mimeTypes: ['image/*'],
  // List of allowed file extensions (with leading '.'), defaults to `''`.
  extensions: ['.png', '.jpg', '.jpeg', '.webp'],
  // Set to `true` for allowing multiple files, defaults to `false`.
  multiple: true,
  // Textual description for file dialog , defaults to `''`.
  description: 'Image files',
  // Suggested directory in which the file picker opens. A well-known directory, or a file or directory handle.
  startIn: 'downloads',
  // By specifying an ID, the user agent can remember different directories for different IDs.
  id: 'projects',
  // Include an option to not apply any filter in the file picker, defaults to `false`.
  excludeAcceptAllOption: true,
};

const blobs = await fileOpen(options);

(2)打开目录

// Options are optional.
const options = {
  // Set to `true` to recursively open files in all subdirectories,
  // defaults to `false`.
  recursive: true,
  // Suggested directory in which the file picker opens. A well-known directory, or a file or directory handle.
  startIn: 'downloads',
  // By specifying an ID, the user agent can remember different directories for different IDs.
  id: 'projects',
  // Callback to determine whether a directory should be entered, return `true` to skip.
  skipDirectory: (entry) => entry.name[0] === '.',
};

const blobs = await directoryOpen(options);

(3)保存文件

// Options are optional. You can pass an array of options, too.
const options = {
  // Suggested file name to use, defaults to `''`.
  fileName: 'Untitled.txt',
  // Suggested file extensions (with leading '.'), defaults to `''`.
  extensions: ['.txt'],
  // Suggested directory in which the file picker opens. A well-known directory, or a file or directory handle.
  startIn: 'downloads',
  // By specifying an ID, the user agent can remember different directories for different IDs.
  id: 'projects',
  // Include an option to not apply any filter in the file picker, defaults to `false`.
  excludeAcceptAllOption: true,
};

// Optional file handle to save back to an existing file.
// This will only work with the File System Access API.
// Get a `FileHandle` from the `handle` property of the `Blob`
// you receive from `fileOpen()` (this is non-standard).
const existingHandle = previouslyOpenedBlob.handle;

// Optional flag to determine whether to throw (rather than open a new file
// save dialog) when `existingHandle` is no longer good, for example, because
// the underlying file was deleted. Defaults to `false`.
const throwIfExistingHandleNotGood = true;

// `blobOrPromiseBlobOrResponse` is a `Blob`, a `Promise<Blob>`, or a `Response`.
await fileSave(
  blobOrResponseOrPromiseBlob,
  options,
  existingHandle,
  throwIfExistingHandleNotGood
);

仅作为个人记录!!

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值