跳转至

webUtils

一个用于与 Web API 对象(File、Blob 等)交互的实用层。

进程:渲染进程

[!IMPORTANT] 如果要在启用了上下文隔离的渲染器进程中调用此 API,请将 API 调用放在预加载脚本中,并使用 contextBridge API 来暴露它。

方法

webUtils 模块包含以下方法:

webUtils.getPathForFile(file)

  • file File - 一个 Web File 对象。

返回 string - 此 File 对象所指向的文件系统路径。如果传入的对象不是 File 对象,则会抛出异常。如果传入的 File 对象是在 JS 中构造的,且并非由磁盘上的文件支持,则返回空字符串。

此方法取代了之前向 File 对象附加 path 属性的做法。下面包含一个示例。

```js @ts-nocheck // Before (renderer) const oldPath = document.querySelector('input[type=file]').files[0].path

```js @ts-nocheck
// After

// Renderer:

const file = document.querySelector('input[type=file]').files[0]
electronApi.doSomethingWithFile(file)

// Preload script:

const { contextBridge, webUtils } = require('electron')

contextBridge.exposeInMainWorld('electronApi', {
  doSomethingWithFile (file) {
    const path = webUtils.getPathForFile(file)
    // Do something with the path, e.g., send it over IPC to the main process.
    // It's best not to expose the full file path to the web content if possible.
  }
})

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron