फ़ाइल एक्सप्लोरर से खोली गई फ़ाइलों को मैनेज करने का तरीका

पालेंस लियाओ
पैलेंस लियाओ

आधुनिक तरीका

फ़ाइल मैनेज करने वाले एपीआई का इस्तेमाल करना

सबसे पहले, अपने वेब ऐप्लिकेशन मेनिफ़ेस्ट में file_handlers एट्रिब्यूट के बारे में बताएं. फ़ाइल हैंडलिंग एपीआई के लिए आपको action प्रॉपर्टी (हैंडलिंग यूआरएल) और accept प्रॉपर्टी के बारे में बताना होगा. यह एक ऑब्जेक्ट है, जिसमें MIME टाइप वाला ऑब्जेक्ट, खास तौर पर उससे जुड़े फ़ाइल एक्सटेंशन की कुंजियों और ऐरे के तौर पर होता है.

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

इसके बाद, आपको 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() का क्लासिक तरीका इस्तेमाल करना

अगर फ़ाइल हैंडलिंग एपीआई काम नहीं करता है, तो भी फ़ाइल एक्सप्लोरर से फ़ाइलों को खींचकर ऐप्लिकेशन में छोड़ा जा सकता है. DataTransferItem.getAsFile() तरीका, ड्रैग डेटा आइटम के File ऑब्जेक्ट को दिखाता है. अगर आइटम कोई फ़ाइल नहीं है, तो यह तरीका null दिखाता है. फ़ाइल को पढ़कर तो सुना जा सकता है, लेकिन उस पर वापस लिखने का कोई तरीका नहीं है. इस तरीके का एक नुकसान यह है कि यह डायरेक्ट्री के साथ काम नहीं करती.

ब्राउज़र सहायता

  • 11
  • 12
  • 50
  • 5.1

सोर्स

प्रोग्रेसिव एन्हैंसमेंट

उपलब्ध होने पर, नीचे दिया गया स्निपेट फ़ाइल हैंडलिंग एपीआई का इस्तेमाल करता है. साथ ही, यह हैंडलर को खींचें और छोड़ें, ताकि ड्रैग की गई फ़ाइलों को मैनेज किया जा सके.

उन फ़ाइल टाइप के बारे में बताएं जिन्हें वेब ऐप्लिकेशन मेनिफ़ेस्ट में मैनेज किया जा सकता है. जो ब्राउज़र, फ़ाइल हैंडलिंग एपीआई के साथ काम नहीं करते वे इसे अनदेखा कर देंगे.

{
  "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>

CSS


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

JS


        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}

`; } }); }