如何處理透過檔案探索工具開啟的檔案

寮國
Paances Liao

首先,請在網頁應用程式資訊清單中宣告 file_handlers 屬性。File Handling API 要求您必須指定 action 屬性 (處理網址) 和 accept 屬性,這是以 MIME 類型表示的物件和陣列,其中具有特別對應副檔名的鍵和陣列。

{
 
"file_handlers": [
   
{
     
"action": "./",
     
"accept": {
       
"image/*": [".jpg", ".jpeg", ".png", ".webp", ".svg"]
     
}
   
}
 
]
}

接下來,您需要使用 File Handling API 透過 launchQueue 強制處理已開啟的檔案。

if ('launchQueue' in window && 'files' in LaunchParams.prototype) {
  launchQueue
.setConsumer((launchParams) => {
   
if (!launchParams.files.length) {
     
return;
   
}
   
for (const fileHandle of launchParams.files) {
     
// Handle the file.
   
}
 
});
}

瀏覽器支援

  • 102
  • 102
  • x
  • x

經典風格

使用傳統版 DataTransferItem.getAsFile() 方法

如果不支援 File Handling API,您仍可從檔案探索工具將檔案拖曳到應用程式中。DataTransferItem.getAsFile() 方法會傳回拖曳資料項目的 File 物件。如果項目不是檔案,此方法會傳回 null。雖然您可以讀取檔案,但無法寫回檔案。這種方法的缺點是不支援目錄。

瀏覽器支援

  • 11
  • 12
  • 50
  • 5.1

資料來源

漸進增強

下方的程式碼片段會在檔案處理時使用 File Handling API,並額外註冊拖曳處理常式,以便處理拖曳的檔案。

宣告可在網頁應用程式資訊清單中處理的檔案類型。瀏覽器如果不支援 File Handling API,則會忽略此 API。

{
 
"file_handlers": [
   
{
     
"action": "./",
     
"accept": {
       
"image/*": [".jpg", ".jpeg", ".png", ".webp", ".svg"]
     
}
   
}
 
]
}
// File Handling API
const handleLaunchFiles = () => {
  window
.launchQueue.setConsumer((launchParams) => {
   
if (!launchParams.files.length) {
     
return;
   
}
    launchParams
.files.forEach(async (handle) => {
     
const file = await handle.getFile();
      console
.log(`File: ${file.name}`);
     
// Do something with the file.
   
});
 
});
};

if ('launchQueue' in window && 'files' in LaunchParams.prototype) {
  handleLaunchFiles
();
}

// This is the drag and drop zone.
const elem = document.querySelector('main');
// Prevent navigation.
elem
.addEventListener('dragover', (e) => {
  e
.preventDefault();
});
// Visually highlight the drop zone.
elem
.addEventListener('dragenter', (e) => {
  elem
.style.outline = 'solid red 1px';
});
// Visually unhighlight the drop zone.
elem
.addEventListener('dragleave', (e) => {
  elem
.style.outline = '';
});
// This is where the drop is handled.
elem
.addEventListener('drop', async (e) => {
 
// Prevent navigation.
  e
.preventDefault();
 
// Unhighlight the drop zone.
  elem
.style.outline = '';
 
// Prepare an array of promises…
 
const fileHandlesPromises = [...e.dataTransfer.items]
   
// …by including only files (where file misleadingly means actual file _or_
   
// directory)…
   
.filter((item) => item.kind === 'file')
   
// …and, depending on previous feature detection…
   
.map((item) => item.getAsFile());
 
// Loop over the array of promises.
 
for await (const handle of fileHandlesPromises) {
   
// This is where we can actually exclusively act on the files.
   
if (handle.isFile) {
      console
.log(`File: ${handle.name}`);
     
// Do something with the file.
   
}
 
}
});

其他資訊

示範

<!DOCTYPE html>
<html lang="en">
 
<head>
   
<meta charset="utf-8" />
   
<meta name="viewport" content="width=device-width, initial-scale=1" />
   
<link rel="manifest" href="manifest.json" />
   
<title>How to handle files opened from the file explorer</title>
   
<link rel="stylesheet" href="style.css" />
   
<!-- TODO: Devsite - Removed inline handlers -->
   
<!-- <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', async () => {
          const registration = await navigator.serviceWorker.register(
            'sw.js',
          );
          console.log(
            'Service worker registered for scope',
            registration.scope,
          );
        });
      }
    </script>
    <script src="script.js" type="module"></script> -->

 
</head>
 
<body>
   
<h1>How to handle files opened from the file explorer</h1>
   
<p>Install the app. After the installation, try opening an image file from the file explorer with the app.
 
</body>
</html>

        html
{
 
box-sizing: border-box;
 
font-family: system-ui, sans-serif;
 
color-scheme: dark light;
}

*, *:before, *:after {
 
box-sizing: inherit;
}

body
{
 
margin: 1rem;
}

img
{
 
height: auto;
 
max-width: 100%;
 
display: block;
}
       

       
if ('launchQueue' in window && 'files' in LaunchParams.prototype) {
  launchQueue
.setConsumer((launchParams) => {
   
if (!launchParams.files.length) {
     
return;
   
}
   
for (const fileHandle of launchParams.files) {
      document
.body.innerHTML += `

${fileHandle.name}

`;
   
}
 
});
}