首頁 > web前端 > js教程 > 主體

在Web上實現文件複製貼上輸入

WBOY
發布: 2024-07-18 16:44:37
原創
728 人瀏覽過

在 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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!