首页  >  文章  >  web前端  >  在Web上实现文件复制粘贴输入

在Web上实现文件复制粘贴输入

WBOY
WBOY原创
2024-07-18 16:44:37866浏览

在 Web 开发领域,收集用户输入时有多种上传文件的方法。其中一种方法是复制粘贴。文件输入的复制粘贴是一种非常直观的用户上传文件的方法。复制粘贴文件输入方法使用户无需记住要上传的文件的位置。在本文中,我们将讨论如何在您的网站上通过复制粘贴实现文件输入。

我们将利用 ClipboadEvent 和 EventTarget 接口来实现复制粘贴文件输入。 ClipboardEvent接口提供了有关粘贴事件的信息,EventTarget接口允许我们监听粘贴事件。

在侦听粘贴事件时,我们将附加一个事件处理函数,在其中决定如何处理粘贴的项目。在我们的例子中,我们将获取粘贴的文件并在其完全加载到浏览器中后立即渲染它。我们将从 HTML 和样式开始。

HTML 和样式

让我们从创建粘贴区域的 HTML 标记开始。下面的代码片段是 HTML 标记:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Copy-Paste File Input</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div 
        id="pasteArea" 
        contenteditable="true" 
        style="border: 2px dashed #ccc; padding: 20px;"
    >
        Paste your file here
    </div>
    <div id="preview"></div>
    <script src="script.js"></script>
</body>
</html>

上面的代码片段呈现了一个矩形容器,我们可以在其中粘贴文件。该容器有一个名为 contenteditable 的属性,设置为 true。 contenteditable 属性对于启用容器中的文件或任何其他项目的粘贴非常重要。如果 contenteditable 属性更改为 false 或删除,粘贴操作将无法按预期工作。我们还有一个ID为preview的容器。我们将使用预览容器来预览用户粘贴的图像。

让我们从 style.css 添加一些基本样式到我们的标记中

*{
    font-family: Arial, Helvetica, sans-serif;
}

body{
    text-align: center;
    margin-block-start: 4rem;
}
#pasteArea {
    border: 2px dashed #ccc;
    padding: 20px;
    width: 300px;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    cursor: pointer;
    margin: auto;
    color: rgb(5, 89, 89);
}

#preview img {
    max-width: 100%;
    margin-top: 10px;
}

上面的标记和样式表创建了一个简单的破折号边框容器,其中包含简单的提示文本,如下面的屏幕截图所示:

Implementing File Input By Copy-Paste on the Web

现在我们已经创建了 UI,让我们在下一节中使用 JavaScript 添加一些有用的功能。

脚本

在本节中,我们将使用 JavaScript 将粘贴事件监听器添加到粘贴区域。在从 DOM 获取粘贴区域以附加事件侦听器之前,我们首先等待 DOM 内容加载,如下面的代码片段所示。

document.addEventListener('DOMContentLoaded', () => {
    const pasteArea = document.querySelector('#pasteArea');

    pasteArea.addEventListener('paste', (event) => {

    });
});

在上面的代码片段中,我们添加了 DOMContentLoaded 事件的监听器。这使得我们可以等待 DOM 树创建后才能获取 DOM 元素。接下来,我们选择粘贴区域容器并向其附加粘贴事件侦听器。

从粘贴的项目中获取文件

粘贴事件处理程序在前面的代码片段中未实现。让我们通过从事件对象获取数据并将它们记录在控制台中来实现它。我们将在本文后面对数据进行更多处理,目前,我们只想确保在将项目粘贴到粘贴区域时接收到文件。下面的代码片段显示了粘贴事件处理程序的最小实现。

pasteArea.addEventListener('paste', (event) => {
        const items = event.clipboardData.items
        for (const item of items) {
            if (item.kind === 'file') {
                const file = item.getAsFile()

                console.log(file)
            }
        }
    })

在上面的代码片段中,我们从 event.clipboardData 对象获取项目。 event.clipboardData.items 是一个 DataTransferItemList,它是一个包含粘贴项目内容的类似列表的对象。这些项目存储在列表中,因为用户可以一次复制和粘贴多个项目。

接下来,我们使用 for ...of 循环迭代项目。在循环中,我们检查每个项目是否是一个文件。如果该项目是“文件”,我们将其作为文件获取并在浏览器的控制台上打印。

在控制台上打印文件信息对于网页的用户来说并不是很有用。让我们在下一节中做一些更有趣的事情。

预览上传的文件

如果我们不在任何地方显示它,那么在将项目粘贴到剪贴板后,用户将很难知道文件上传是否成功。通过显示指示成功的内容来表明文件已成功上传非常重要。还有什么比显示上传文件本身更好的指示上传成功的方法呢?

在本节中,我们将扩展粘贴事件处理程序以从接收到的文件创建 URL。文件加载到浏览器后,我们将使用创建的 URL 来呈现该文件。我们将利用 FileReader API 从文件创建 URL,如下面代码片段中的代码所示。

pasteArea.addEventListener('paste', (event) => {
        const items = event.clipboardData.items
        for (const item of items) {
            if (item.kind === 'file') {
                const file = item.getAsFile()


                const reader = new FileReader();

                reader.onloadend = (e) => {
                    const url = e.target.result
                    console.log(url)

                };
                reader.readAsDataURL(file);
            }
        }
    });

在上面的代码片段中,我们创建了 FileReader 的实例并使用它来生成数据 URL。我们还向 FileReader 对象附加了一个 loadend 事件侦听器,我们将读取结果记录到控制台。这是预览文件的第一步,我们现在可以使用 URL 来显示文件。

Assuming the user pasted image files, the following code snippet shows how we can extend the event handler to create a URL and display the image file.

 reader.onloadend = (e) => {
       const url = e.target.result
       const preview = document.querySelector('#preview')
       const img = document.createElement('img');

       img.src = url;
       preview.appendChild(img);
   };

In the code snippet above, we get the preview container from the DOM and create an img element for rendering the image. We assign the created URL as the src of the image and append the image to the preview container. Once the image is appended to the preview container, the user can now know that the image they pasted was successfully loaded into the web page.

Success! We have successfully implemented file uploads by copy-paste on a webpage. This method of file upload gives users the privilege of uploading files easily without the need to click several buttons to select the file to be uploaded. The ClipboadEvent interface provides an easy way to collect data from items pasted on the browser. The FileReader interface allows us to create a URL from the uploaded file and use it to preview the uploaded file.

Feel free to say something in the comment section. Find more about the ClipBoardEvent and the FileReader interfaces from MDN.

以上是在Web上实现文件复制粘贴输入的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn