Altbilgi içeriğine atla
NODE YARDıM

dropzone npm (Geliştiriciler İçin Nasıl Çalışır)

Dosya yükleme, web uygulamalarında yaygın bir özelliktir ve kullanıcı dostu hale getirmek, iyi bir kullanıcı deneyimi için kritik öneme sahiptir. Bu süreci basitleştiren popüler bir kütüphane Dropzone.js. React ile birleştirildiğinde, Dropzone, dosya yüklemelerini sürükle-bırak yoluyla uygulamak için güçlü bir araç olabilir. react-dropzone, minimal geliştirme çabalarıyla sorunsuz ve mükemmel bir şekilde entegre olur. Bu makale, Dropzone'u React uygulamasıyla entegre etme konusunda rehberlik edecek ve Dropzone.js kütüphanesi etrafında mükemmel bir sarıcı olan react-dropzone paketini kullanıma sunacaktır.

Bu makalede ayrıca PDF belgeleri oluşturmak, düzenlemek ve yönetmek için IronPDF NPM paketini de inceleyeceğiz.

React'ta Neden Dropzone Kullanmalı?

Dropzone, dosya yüklemeyi sorunsuz hale getiren çeşitli özellikler sunar:

1. Sürükle ve Bırak Arayüzü

Kullanıcıların dosya seçimi sağlamak ve dosya diyaloğu eklemek için dosyaları sürükleyip bırakmasına olanak tanır.

2. Önizlemeler

Düşürülen dosyalardan varsayılan görüntü küçük resim önizlemeleri görüntüler ve UI okunabilirliğini artırır.

3. Çoklu Dosya Yüklemeleri

Bir defada birden fazla dosya yüklemeyi destekler.

4. Özelleştirilebilir

Çeşitli seçenekler ve geri aramalar ile oldukça özelleştirilebilir. Dosya diyaloğu açma veya dosya seçme diyaloglarını özelleştirebilirsiniz.

5. Büyük Dosyalar İçin Parçalı Yüklemeler

Büyük dosyaları parçalı yüklemeler kullanarak yükler.

6. Olayları Yönetme

Dosya diyaloğu iptal geri çağrısı ve tarayıcı görüntü boyutlandırma olayları yönetilebilir.

React Uygulamasını Ayarlama

Dropzone'u entegre etmeden önce bir React uygulamanızın kurulu olduğundan emin olun. Eğer sahip değilseniz, Create React App kullanarak yeni bir React projesi oluşturabilirsiniz:

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

react-dropzone Kurulumu

React projenizde Dropzone kullanmak için react-dropzone paketi kurmanız gerekmektedir:

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

react-dropzone'un Temel Kullanımı

İşte bir React bileşeninde react-dropzone kullanımına basit bir örnek:

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

Dosya Yüklemelerini Yönetme

Dosyalar bırakıldığında veya seçildiğinde, onDrop geri çağrısı kabul edilen dosyaların bir dizisini alır. Ardından dosyaları, örneğin bir sunucuya yüklemek gibi işleyebilirsiniz. İşte dosyaları fetch kullanarak yüklemek için onDrop geri çağrısını nasıl genişletebileceğiniz:

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

Önizlemeleri Görüntüleme

Yüklenen dosyaların önizlemelerini de görüntüleyebilirsiniz. Bunu nasıl yapacağınızın bir örneği burada:

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

Temizlik Yapma

Bellek sızıntılarını önlemek için nesne URL'lerini iptal etmek önemlidir. Bunu, useEffect kancasını kullanarak gerçekleştirebilirsiniz:

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 Tanıtımı

IronPDF, Node.js uygulamalarında PDF oluşturmayı kolaylaştırmak için tasarlanmış güçlü bir npm paketidir. HTML içeriğinden, URL'lerden veya hatta mevcut PDF dosyalarından PDF belgeleri oluşturmanıza olanak tanır. Fatura, rapor veya başka herhangi bir türde belge oluşturuyor olun, IronPDF süreci, sezgisel API ve güçlü özellik seti ile basitleştirir.

IronPDF'in Ana Özellikleri Arasında

1. HTML'den PDF'ye Dönüşüm

HTML içeriğini kolayca PDF belgelerine dönüştürün. Bu özellik, web içeriğinden dinamik PDF'ler oluşturmak için özellikle kullanışlıdır.

2. URL'den PDF'ye Dönüşüm

URL'lerden doğrudan PDF'ler oluşturun. Bu, web sayfalarının içeriğini yakalamanıza ve bunları programatik olarak PDF dosyaları olarak kaydetmenize olanak tanır.

3. PDF Manipülasyonu

Mevcut PDF belgelerini birleşik, parçalara ayırın ve kolayca manipüle edin. IronPDF, sayfaların eklenmesi, belgelerin bölünmesi ve daha fazlasını içeren, PDF dosyalarını manipüle etme işlevsellikleri sağlar.

4. PDF Güvenlik

PDF belgelerinizi parolalarla şifreleyerek veya dijital imzalar uygulayarak güvence altına alın. IronPDF, hassas belgelerinizi yetkisiz erişime karşı koruma seçenekleri sunar.

5. Yüksek Kalite Çıktı

Metin, görseller ve biçimlendirmeyi doğru şekilde render ederek yüksek kaliteli PDF belgeler üretilir. IronPDF, oluşturduğunuz PDF'lerin orijinal içeriğe sadık kalmasını sağlar.

6. Çapraz Platform Uyumluluğu

IronPDF, Windows, Linux ve macOS dahil olmak üzere çeşitli platformlarla uyumludur ve geniş bir geliştirme ortamı yelpazesine uygundur.

7. Basit Entegrasyon

IronPDF, npm paketi kullanarak Node.js uygulamalarınıza kolayca entegre edilir. API, iyi belgelenmiştir ve projelerinize PDF oluşturma yeteneklerini entegre etmeyi kolaylaştırır.

Bir web uygulaması, sunucu tarafı betiği veya komut satırı aracı oluşturuyorsanız, IronPDF, profesyonel kalitede PDF belgeleri verimli ve güvenilir bir şekilde oluşturmanızı sağlar.

IronPDF kullanarak PDF Belgesi Oluşturun ve Dropzone NPM paketini kullanın

Bağımlılıkları Kurun: İlk olarak, yeni bir Next.js projesi oluşturun (henüz oluşturmadıysanız) ve aşağıdaki komutu kullanın: Kurulum sayfasına başvurun.

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

Sonrasında, proje dizinine gidin:

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

Gerekli paketleri kurun:

npm install @ironsoftware/ironpdf, react-dropzone

Bir PDF oluşturun: Şimdi, IronPDF kullanarak bir PDF oluşturmanın basit bir örneğini oluşturalım. Next.js bileşeninizde (ör. pages/index.tsx) aşağıdaki kodu ekleyin:

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 sadece Node'da çalıştığı için, uygulama için PDF'nin Node'da oluşturulacağı bir API ekleyin.

Aşağıdaki kaynak kodu ekleyerek pages/api klasörüne bir pdf.js dosyası oluşturun:

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

Not: Yukarıdaki kodda, kendi lisans anahtarınızı eklediğinizden emin olun.

Uygulamanızı Çalıştırın: Next.js uygulamanızı başlatın:

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

Şimdi, bir web sitesi URL'si girin ve "PDF Oluştur" tıklayın. Aşağıda gösterildiği gibi, awesomeIron.pdf adlı bir dosya indirilecektir.

Şimdi Dropzone'a tıklayın ve indirilen dosyayı seçin. Bu, dosyanın alt kısmında adıyla birlikte bir önizlemesini gösterecektir: awesomeIron.pdf.

IronPDF Lisansı

IronPDF sayfasına lisanslama detayları için başvurun.

Lisans Anahtarını aşağıda gösterildiği gibi uygulamaya yerleştirin:

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

Sonuç

Dropzone ile React'i react-dropzone kullanarak entegre etmek, dosya yükleme deneyimini önemli ölçüde iyileştiren basit bir süreçtir. Sürükle ve bırak, dosya önizlemeleri ve kapsamlı özelleştirme seçenekleri gibi özelliklerle react-dropzone, React projelerinize değerli bir katkı olabilir. Yeteneklerini keşfetmeye ve uygulamanızın ihtiyaçlarına uygun hale getirmeye başlayın!

IronPDF ise, uygulamalara kolayca entegre edilebilen çok yönlü bir PDF oluşturma ve manipülasyon kütüphanesidir. IronPDF, geliştiricilerin başlamasına yardımcı olmak için eksiksiz belgelendirme ve kod örnekleri sunar.

Bu makalede belirtilen adımları izleyerek, React uygulamanızda sağlam bir dosya yükleme bileşeni oluşturabilir ve modern uygulamalara PDF dosyası oluşturma yeteneklerini entegre edebilirsiniz.

Darrius Serrant
Tam Yığın Yazılım Mühendisi (WebOps)

Darrius Serrant, Miami Üniversitesi'nden Bilgisayar Bilimi alanında Lisans Derecesine sahip ve Iron Software'de Tam Yığın WebOps Pazarlama Mühendisi olarak çalışıyor. Genç yaşlardan itibaren kodlamaya çekildi, bilgisayar bilimi hem gizemli hem de erişilebilir olarak görüldü ve bu özellik, yaratıcılık ...

Daha Fazla Oku

Iron Destek Ekibi

Haftada 5 gün, 24 saat çevrimiçiyiz.
Sohbet
E-posta
Beni Ara