브라우저에 파일을 붙여넣는 작업은 HTMLElement의 paste 이벤트를 사용하는 것으로 구성됩니다.
HTMLElement의 paste 이벤트 사용
첫 번째 단계로 원하는 요소에 paste 이벤트의 이벤트 리스너를 추가합니다. 일반적으로 이는 document 수준이므로 특정 요소에 포커스를 맞출 필요가 없습니다. 다음으로
Clipboard 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);
}
});
});