IRONSOFTWAREHOME
NODE 說明

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

Curtis Chau
Curtis Chau
Updated: 2026年6月20日

在網頁應用程式中,檔案上傳是一個常見的功能,讓其使用起來簡便對於良好的使用者體驗至關重要。 一個能簡化這個過程的流行函式庫是Dropzone.js。 當與React結合使用時,Dropzone可以成為實現拖放檔案上傳的強大工具。 react-dropzone能夠完美且無縫地整合,僅需最少的開發投入。 這篇文章將指導您如何使用react-dropzone套件將Dropzone整合到React應用程式中,它是Dropzone.js函式庫的一個優秀外包裝。

在這篇文章中,我們也會看一下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
SHELL

安裝react-dropzone

要在React專案中使用Dropzone,您需要安裝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;
Text

處理檔案上傳

當檔案被拖放或選擇時,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
}, []);
Text

顯示預覽

您還可以顯示已上傳文件的預覽。 這是一個如何做到這一點的例子:

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;
Text

清理

撤銷物件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]);
Text

介紹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. 簡單整合

using npm 套件輕鬆將 IronPDF 整合到您的 Node.js 應用中。 API 文件完善,便於在您的專案中加入 PDF 生成功能。

無論您是在構建一個網頁應用程式、一個伺服器端腳本還是一個命令行工具,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"
SHELL

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

cd demo-dropzone-ironpdf
SHELL

安裝所需的套件:

> npm install @ironsoftware/ironpdf, react-dropzone

建立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>
    );
}
Text

由於IronPDF僅在Node上運行,因此接下來在應用程式中新增生成PDF應用的API。

在pages/api並新增下面的原始碼:

// 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
SHELL

現在,輸入網站URL以生成PDF並點擊"生成PDF"。 下面將下載一個名為awesomeIron.pdf的文件。

現在點擊Dropzone並選擇下載的文件。這將顯示文件的預覽名稱,顯示在底部:awesomeIron.pdf。

IronPDF 授權

請參考IronPDF頁面以獲取授權詳細資訊。

將授權金鑰放置在應用程式中,如下所示:

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

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

結論

使用react-dropzone將Dropzone與React整合是一個直接且能顯著增強文件上傳體驗的過程。 使用像拖放、文件預覽和廣泛的自訂選項這樣的功能,react-dropzone可以成為您React專案中的一個有價值的補充。 開始探索它的功能,並根據您的應用需求進行調整!

IronPDF則是一個多功能的PDF生成和操作函式庫,能夠輕鬆整合到應用程式中。 IronPDF提供詳細的文件和程式碼範例來幫助開發人員入門。

通過遵循本文中概述的步驟,您可以在React應用程式中建立一個強大的文件上傳組件,並將PDF文件生成能力整合到現代應用程式中。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰。

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

OR
bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
預訂您的免費線上演示
Booking Badge

獲得來自全球數百萬工程師的信賴

Iron Software的客戶徽標
獲取您的無義務諮詢
填寫以下表格或發送電子郵件至sales@ironsoftware.com
您的資料將始終保密。
獲得來自全球數百萬工程師的信賴
Iron Software的客戶徽標
立即獲取您的30天試用金鑰。
無需信用卡或帳戶建立
C# 用於PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝
C# PDF DLL
下載DLL

版本: 2026.9

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"

授權從$999起