要将文件粘贴到浏览器中,需要使用 HTMLElement
的 paste
事件。
使用 HTMLElement
的 paste
事件
首先,您需要在所需元素(通常是在 document
级别)为 paste
事件添加事件监听器,因此不需要聚焦任何特定元素。接下来,您将使用 Clipboard API,该 API 可让您访问 HTMLElement
的 paste
事件的 clipboardData
字段,然后您可以遍历其 files
列表。根据粘贴的每个文件的 MIME 类型,您可以决定是将其呈现到屏幕上(对于图片或视频),还是将文件的文本内容粘贴到(例如对于文本文件)中的 textarea
元素中。
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);
}
});
});
深入阅读
演示
HTML
<!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>
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
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);
}
});
});