如何貼上檔案

哈利.西奧多羅 (Harry Theodoulou)
Harry Theodoulou

將檔案貼入瀏覽器時,需要使用 HTMLElementpaste 事件。

首先,您會在所需元素中為 paste 事件新增事件監聽器,這通常位於 document 層級,因此無須聚焦特定元素。接下來,請使用 Clipboard API,藉此存取 HTMLElement paste 事件的 clipboardData 欄位,接著您就可以對其 files 清單進行疊代作業。根據貼上的每個檔案的 MIME 類型,您可以決定要在螢幕上轉譯 (例如圖片或影片),還是要將檔案的文字內容 (例如在文字檔中) 貼入 textarea 元素。

瀏覽器支援

  • 66
  • 79
  • 63
  • 13.1

資料來源

document.addEventListener('paste', async (e) => {
 
// Prevent the default behavior, so you can code your own logic.
  e
.preventDefault();
 
if (!e.clipboardData.files.length) {
   
return;
 
}
 
// Iterate over all pasted files.
 
Array.from(e.clipboardData.files).forEach(async (file) => {
   
// Add more checks here for MIME types you're interested in,
   
// such as `application/pdf`, `video/mp4`, etc.
   
if (file.type.startsWith('image/')) {
     
// For images, create an image and append it to the `body`.
     
const img = document.createElement('img');
     
const blob = URL.createObjectURL(file);
      img
.src = blob;
      document
.body.append(img);
   
} else if (file.type.startsWith('text/')) {
     
// For text files, read the contents and output it into a `textarea`.
     
const textarea = document.createElement('textarea');
      textarea
.value = await file.text();
      document
.body.append(textarea);
   
}
 
});
});

其他資訊

示範

<!DOCTYPE html>
<html>
 
<head>
   
<title>How to paste files</title>
 
</head>
 
<body>
   
<h1>How to paste files</h1>
   
<p>Hit <kbd></kbd> + <kbd>v</kbd> (for macOS) or <kbd>ctrl</kbd> + <kbd>v</kbd>
      (for other operating systems) to paste image or text file(s) anywhere in this page.
   
</p>
 
</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;
}
       

        document
.addEventListener('paste', async (e) => {
 
// Prevent the default behavior, so you can code your own logic.
  e
.preventDefault();
 
if (!e.clipboardData.files.length) {
   
return;
 
}
 
// Iterate over all pasted files.
 
Array.from(e.clipboardData.files).forEach(async (file) => {
   
// Add more checks here for MIME types you're interested in,
   
// such as `application/pdf`, `video/mp4`, etc.
   
if (file.type.startsWith('image/')) {
     
// For images, create an image and append it to the `body`.
     
const img = document.createElement('img');
     
const blob = URL.createObjectURL(file);
      img
.src = blob;
      document
.body.append(img);
   
} else if (file.type.startsWith('text/')) {
     
// For text files, read the contents and output it into a `textarea`.
     
const textarea = document.createElement('textarea');
      textarea
.value = await file.text();
      document
.body.append(textarea);
   
}
 
});
});