跳過到頁腳內容
NODE 說明

dropzone npm(開發者的使用方法)

文件上傳是網頁應用程式中的常見功能,使其易於使用對於良好的用戶體驗至關重要。 Dropzone.js是一個可以簡化此過程的流行函式庫。 當與React結合使用時, Dropzone可以成為實現拖放檔案上傳的強大工具。 react-dropzone可以完美無縫地集成,只需極少的開發工作。 本文將指導您如何使用 react-dropzone 套件(Dropzone.js 程式庫的優秀封裝套件)將Dropzone整合到 React 應用程式中。

本文也將介紹IronPDF NPM 包,用於產生、編輯和管理 PDF 文件。

為什麼要在 React 中使用 Dropzone?

Dropzone提供多種功能,讓檔案上傳變得輕鬆方便:

1. 拖放式介面

允許使用者拖放檔案以啟用檔案選擇功能,並以程式設計方式新增檔案對話方塊。

2. 預覽

顯示拖放檔案的預設影像縮圖預覽,增強使用者介面可讀性。

3. 多文件上傳

支援一次上傳多個文件。

4. 可自訂

高度可定制,提供多種選項和回調函數。 您可以自訂檔案對話方塊的開啟方式或檔案選擇對話方塊。

5. 大檔案分塊上傳

使用分塊上傳方式上傳大檔案。

6. 處理事件

可以處理檔案對話方塊取消回呼和瀏覽器影像調整大小事件。

設定 React 應用程式

在整合 Dropzone 之前,請確保您已設定好 React 應用程式。如果沒有,您可以使用Create React App建立一個新的 React 專案:

npx create-react-app dropzone-demo
cd dropzone-demo
npx create-react-app dropzone-demo
cd dropzone-demo
SHELL

安裝 react-dropzone

要在您的 React 專案中使用 Dropzone,您需要安裝react-dropzone 套件

npm install react-dropzone
# or
yarn add react-dropzone
npm install react-dropzone
# or
yarn add react-dropzone
SHELL

react-dropzone 的基本用法

以下是一個在 React 元件中使用 react-dropzone 的簡單範例:

import React, { useCallback } from 'react';
import { useDropzone } from 'react-dropzone';

// DropzoneComponent is a React component demonstrating basic usage of react-dropzone
const DropzoneComponent = () => {
  // Callback to handle file drops
  const onDrop = useCallback((acceptedFiles) => {
    console.log(acceptedFiles); // Log the accepted files
  }, []);

  // Extracted properties from useDropzone hook
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div {...getRootProps()} style={dropzoneStyle}>
      <input {...getInputProps()} />
      {
        isDragActive ? 
          <p>Drop the files here ...</p> : 
          <p>Drag 'n' drop some files here, or click to select files</p>
      }
    </div>
  );
};

// Styles for the dropzone area
const dropzoneStyle = {
  border: '2px dashed #0087F7',
  borderRadius: '5px',
  padding: '20px',
  textAlign: 'center',
  cursor: 'pointer'
};

export default DropzoneComponent;
import React, { useCallback } from 'react';
import { useDropzone } from 'react-dropzone';

// DropzoneComponent is a React component demonstrating basic usage of react-dropzone
const DropzoneComponent = () => {
  // Callback to handle file drops
  const onDrop = useCallback((acceptedFiles) => {
    console.log(acceptedFiles); // Log the accepted files
  }, []);

  // Extracted properties from useDropzone hook
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div {...getRootProps()} style={dropzoneStyle}>
      <input {...getInputProps()} />
      {
        isDragActive ? 
          <p>Drop the files here ...</p> : 
          <p>Drag 'n' drop some files here, or click to select files</p>
      }
    </div>
  );
};

// Styles for the dropzone area
const dropzoneStyle = {
  border: '2px dashed #0087F7',
  borderRadius: '5px',
  padding: '20px',
  textAlign: 'center',
  cursor: 'pointer'
};

export default DropzoneComponent;
JAVASCRIPT

處理文件上傳

當檔案被拖曳或選取時, onDrop回呼函數會接收一個已接受檔案的陣列。 然後您可以處理這些文件,例如將它們上傳到伺服器。 以下是如何擴充 onDrop 回呼函數以使用 fetch 上傳檔案的方法:

// onDrop callback to handle file uploads
const onDrop = useCallback((acceptedFiles) => {
  const formData = new FormData();
  // Append each file to the formData
  acceptedFiles.forEach((file) => {
    formData.append('files', file);
  });

  // Send a POST request to upload the files
  fetch('https://your-upload-endpoint', {
    method: 'POST',
    body: formData,
  })
  .then(response => response.json()) // Parse the JSON from the response
  .then(data => console.log(data)) // Log the response data
  .catch(error => console.error('Error:', error)); // Handle errors
}, []);
// onDrop callback to handle file uploads
const onDrop = useCallback((acceptedFiles) => {
  const formData = new FormData();
  // Append each file to the formData
  acceptedFiles.forEach((file) => {
    formData.append('files', file);
  });

  // Send a POST request to upload the files
  fetch('https://your-upload-endpoint', {
    method: 'POST',
    body: formData,
  })
  .then(response => response.json()) // Parse the JSON from the response
  .then(data => console.log(data)) // Log the response data
  .catch(error => console.error('Error:', error)); // Handle errors
}, []);
JAVASCRIPT

顯示預覽

您也可以顯示已上傳文件的預覽。 以下是一個操作範例:

import React, { useCallback, useState } from 'react';
import { useDropzone } from 'react-dropzone';

const DropzoneComponent = () => {
  const [files, setFiles] = useState([]);

  // onDrop callback to handle file drops and generate previews
  const onDrop = useCallback((acceptedFiles) => {
    setFiles(acceptedFiles.map(file => Object.assign(file, {
      preview: URL.createObjectURL(file)
    })));
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  // Generate thumbnails for each file
  const thumbs = files.map(file => (
    <div key={file.name}>
      <img
        src={file.preview}
        style={{ width: '100px', height: '100px' }}
        alt={file.name}
      />
    </div>
  ));

  return (
    <div>
      <div {...getRootProps()} style={dropzoneStyle}>
        <input {...getInputProps()} />
        {
          isDragActive ? 
            <p>Drop the files here ...</p> : 
            <p>Drag 'n' drop some files here, or click to select files</p>
        }
      </div>
      <div>
        {thumbs}
      </div>
    </div>
  );
};

// Styles for the dropzone area
const dropzoneStyle = {
  border: '2px dashed #0087F7',
  borderRadius: '5px',
  padding: '20px',
  textAlign: 'center',
  cursor: 'pointer'
};

export default DropzoneComponent;
import React, { useCallback, useState } from 'react';
import { useDropzone } from 'react-dropzone';

const DropzoneComponent = () => {
  const [files, setFiles] = useState([]);

  // onDrop callback to handle file drops and generate previews
  const onDrop = useCallback((acceptedFiles) => {
    setFiles(acceptedFiles.map(file => Object.assign(file, {
      preview: URL.createObjectURL(file)
    })));
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  // Generate thumbnails for each file
  const thumbs = files.map(file => (
    <div key={file.name}>
      <img
        src={file.preview}
        style={{ width: '100px', height: '100px' }}
        alt={file.name}
      />
    </div>
  ));

  return (
    <div>
      <div {...getRootProps()} style={dropzoneStyle}>
        <input {...getInputProps()} />
        {
          isDragActive ? 
            <p>Drop the files here ...</p> : 
            <p>Drag 'n' drop some files here, or click to select files</p>
        }
      </div>
      <div>
        {thumbs}
      </div>
    </div>
  );
};

// Styles for the dropzone area
const dropzoneStyle = {
  border: '2px dashed #0087F7',
  borderRadius: '5px',
  padding: '20px',
  textAlign: 'center',
  cursor: 'pointer'
};

export default DropzoneComponent;
JAVASCRIPT

清理

撤銷物件 URL 是避免記憶體洩漏的必要步驟。 您可以使用 useEffect 鉤子來實現這一點:

import { useEffect } from 'react';

// useEffect to clean up object URLs to prevent memory leaks
useEffect(() => {
  // Revoke the data URIs
  return () => files.forEach(file => URL.revokeObjectURL(file.preview));
}, [files]);
import { useEffect } from 'react';

// useEffect to clean up object URLs to prevent memory leaks
useEffect(() => {
  // Revoke the data URIs
  return () => files.forEach(file => URL.revokeObjectURL(file.preview));
}, [files]);
JAVASCRIPT

介紹 IronPDF。

IronPDF是一個功能強大的 npm 包,旨在簡化 Node.js 應用程式中的 PDF 生成過程。 它允許您從HTML 內容URL甚至現有的 PDF 文件建立 PDF 文件。 無論您是產生發票、報告或任何其他類型的文檔, IronPDF都能憑藉其直觀的API和強大的功能集簡化流程。

IronPDF 的主要功能包括

1.HTML 至 PDF 轉換

輕鬆將HTML內容轉換為PDF文件。 此功能對於從網頁內容產生動態 PDF 特別有用。

2. URL 轉 PDF

直接從URL產生PDF文件。 這樣,您就可以透過程式擷取網頁內容並將其儲存為 PDF 檔案。

3. PDF 處理

輕鬆合併、分割和操作現有 PDF 文件。 IronPDF 提供操作 PDF 檔案的功能,例如追加頁面、分割文件等等。

4.PDF安全性

使用密碼加密或套用數位簽章來保護您的 PDF 文件。 IronPDF 提供多種選項,保護您的敏感文件免受未經授權的存取。

5. 高品質輸出

產生高品質的 PDF 文檔,精確呈現文字、圖像和格式。 IronPDF 可確保您產生的 PDF 檔案與原始內容一致。

6. 跨平台相容性

IronPDF 與包括 Windows、Linux 和 macOS 在內的各種平台相容,使其適用於各種開發環境。

7. 簡易集成

使用 IronPDF 的 npm 包,即可輕鬆整合到您的 Node.js 應用程式中。 該 API 文件齊全,可以輕鬆地將 PDF 生成功能整合到您的專案中。

無論您是建立 Web 應用程式、伺服器端腳本或命令列工具, IronPDF都能讓您有效率且可靠地建立專業級 PDF 文件。

使用 IronPDF 產生 PDF 文檔,並使用 Dropzone NPM 包

安裝依賴項:首先,使用下列命令建立新的 Next.js 專案(如果還沒有):請參閱設定頁面

npx create-next-app@latest demo-dropzone-ironpdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest demo-dropzone-ironpdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

接下來,導航到您的專案目錄:

cd demo-dropzone-ironpdf
cd demo-dropzone-ironpdf
SHELL

安裝所需軟體包:

npm install @ironsoftware/ironpdf
npm install react-dropzone
npm install @ironsoftware/ironpdf
npm install react-dropzone
SHELL

建立 PDF :現在,讓我們建立一個使用 IronPDF 產生 PDF 的簡單範例。 在您的 Next.js 元件(例如 pages/index.tsx)中,加入以下程式碼:

import Head from 'next/head';
import styles from '../styles/Home.module.css';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useState } from "react";
import DropzoneComponent from "../components/mydropzone";

export default function Home() {
    const [textInput, setTextInput] = useState('');

    // Function to display different types of toast messages
    const notify = () => {
        toast.success("Success! This is a success message.", {
            position: "top-right"
        });
        toast.info("Information message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.error("Error message", {
            className: 'custom-toast',
            style: { background: 'red', color: 'white' }
        });
    };

    // Function to generate and download a PDF
    const generatePdf = async () => {
        try {
            const response = await fetch('/api/pdf?url=' + textInput);
            const blob = await response.blob();
            const url = window.URL.createObjectURL(new Blob([blob]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'awesomeIron.pdf');
            document.body.appendChild(link);
            link.click(); // Trigger the download
            link.parentNode.removeChild(link); // Remove the link
        } catch (error) {
            console.error('Error generating PDF:', error);
        }
    };

    // Handle changes in the text input field
    const handleChange = (event) => {
        setTextInput(event.target.value);
    }

    return (
        <div className={styles.container}>
            <Head>
                <title>Generate PDF Using IronPDF</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <main>
                <h1>Demo Drop Zone and Generate PDF Using IronPDF</h1>
                <DropzoneComponent />
                <p>
                    <span>Enter Url To Convert to PDF:</span>{" "}
                </p>
                <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>Generate PDF</button>
            </main>
            <style jsx>{`
                main {
                    padding: 5rem 0;
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                }
                footer {
                    width: 100%;
                    height: 100px;
                    border-top: 1px solid #eaeaea;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
                footer img {
                    margin-left: 0.5rem;
                }
                footer a {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    text-decoration: none;
                    color: inherit;
                }
                code {
                    background: #fafafa;
                    border-radius: 5px;
                    padding: 0.75rem;
                    font-size: 1.1rem;
                    font-family: Menlo,
                    Monaco,
                    Lucida Console,
                    Liberation Mono,
                    DejaVu Sans Mono,
                    Bitstream Vera Sans Mono,
                    Courier New,
                    monospace;
                }
            `}</style>
            <style jsx global>{`
                html,
                body {
                    padding: 0;
                    margin: 0;
                    font-family: -apple-system,
                    BlinkMacSystemFont,
                    Segoe UI,
                    Roboto,
                    Oxygen,
                    Ubuntu,
                    Cantarell,
                    Fira Sans,
                    Droid Sans,
                    Helvetica Neue,
                    sans-serif;
                }
                * {
                    box-sizing: border-box;
                }
            `}</style>
        </div>
    );
}
import Head from 'next/head';
import styles from '../styles/Home.module.css';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useState } from "react";
import DropzoneComponent from "../components/mydropzone";

export default function Home() {
    const [textInput, setTextInput] = useState('');

    // Function to display different types of toast messages
    const notify = () => {
        toast.success("Success! This is a success message.", {
            position: "top-right"
        });
        toast.info("Information message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.error("Error message", {
            className: 'custom-toast',
            style: { background: 'red', color: 'white' }
        });
    };

    // Function to generate and download a PDF
    const generatePdf = async () => {
        try {
            const response = await fetch('/api/pdf?url=' + textInput);
            const blob = await response.blob();
            const url = window.URL.createObjectURL(new Blob([blob]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'awesomeIron.pdf');
            document.body.appendChild(link);
            link.click(); // Trigger the download
            link.parentNode.removeChild(link); // Remove the link
        } catch (error) {
            console.error('Error generating PDF:', error);
        }
    };

    // Handle changes in the text input field
    const handleChange = (event) => {
        setTextInput(event.target.value);
    }

    return (
        <div className={styles.container}>
            <Head>
                <title>Generate PDF Using IronPDF</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <main>
                <h1>Demo Drop Zone and Generate PDF Using IronPDF</h1>
                <DropzoneComponent />
                <p>
                    <span>Enter Url To Convert to PDF:</span>{" "}
                </p>
                <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>Generate PDF</button>
            </main>
            <style jsx>{`
                main {
                    padding: 5rem 0;
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                }
                footer {
                    width: 100%;
                    height: 100px;
                    border-top: 1px solid #eaeaea;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
                footer img {
                    margin-left: 0.5rem;
                }
                footer a {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    text-decoration: none;
                    color: inherit;
                }
                code {
                    background: #fafafa;
                    border-radius: 5px;
                    padding: 0.75rem;
                    font-size: 1.1rem;
                    font-family: Menlo,
                    Monaco,
                    Lucida Console,
                    Liberation Mono,
                    DejaVu Sans Mono,
                    Bitstream Vera Sans Mono,
                    Courier New,
                    monospace;
                }
            `}</style>
            <style jsx global>{`
                html,
                body {
                    padding: 0;
                    margin: 0;
                    font-family: -apple-system,
                    BlinkMacSystemFont,
                    Segoe UI,
                    Roboto,
                    Oxygen,
                    Ubuntu,
                    Cantarell,
                    Fira Sans,
                    Droid Sans,
                    Helvetica Neue,
                    sans-serif;
                }
                * {
                    box-sizing: border-box;
                }
            `}</style>
        </div>
    );
}
JAVASCRIPT

由於 IronPDF 只能在 Node 上運行,接下來需要為應用程式新增一個 API,以便在 Node 上產生 PDF。

pages/api資料夾下建立一個名為pdf.js文件,並將以下原始程式碼新增至該文件:

// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";

export default async function handler(req, res) {
    try {
        const url = req.query.url;
        const pdf = await PdfDocument.fromUrl(url);
        const data = await pdf.saveAsBuffer();
        console.log('PDF data:', data);

        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', 'attachment; filename=awesomeIron.pdf');
        res.send(data);
    } catch (error) {
        console.error('Error generating PDF:', error);
        res.status(500).end();
    }
}
// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";

export default async function handler(req, res) {
    try {
        const url = req.query.url;
        const pdf = await PdfDocument.fromUrl(url);
        const data = await pdf.saveAsBuffer();
        console.log('PDF data:', data);

        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', 'attachment; filename=awesomeIron.pdf');
        res.send(data);
    } catch (error) {
        console.error('Error generating PDF:', error);
        res.status(500).end();
    }
}
JAVASCRIPT

注意:在上面的程式碼中,請務必新增您自己的許可證金鑰。

運行您的應用程式:啟動您的 Next.js 應用程式:

npm run dev
# or
yarn dev
npm run dev
# or
yarn dev
SHELL

現在,輸入要產生 PDF 的網站 URL,然後點擊"產生 PDF"。 將會下載一個名為awesomeIron.pdf的文件,如下圖所示。

現在點擊"拖放區",選擇下載的檔案。這將顯示文件的預覽,文件名稱顯示在底部: awesomeIron.pdf

IronPDF 授權。

有關許可詳情,請參閱IronPDF頁面。

按照下圖所示,將許可證金鑰貼到應用程式中:

import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
JAVASCRIPT

結論

使用react-dropzoneDropzone與 React 整合是一個簡單的過程,可以顯著提昇文件上傳體驗。 react-dropzone 具有拖放、文件預覽和豐富的自訂選項等功能,可成為您 React 專案的寶貴補充。 開始探索它的各項功能,並根據您的應用需求進行客製化!

另一方面, IronPDF是一個功能全面的 PDF 生成和處理庫,可以輕鬆整合到應用程式中。 IronPDF 提供詳盡的文件程式碼範例,幫助開發人員快速入門。

按照本文概述的步驟,您可以在 React 應用程式中建立一個強大的文件上傳元件,還可以將 PDF 文件生成功能整合到現代應用程式中。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。