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 çok önemlidir. Bu süreci basitleştiren popüler bir kütüphane Dropzone.js'dir. React ile birleştirildiğinde, Dropzone, dosya yükleme için sürükle ve bırak işlevselliği uygulanmasında güçlü bir araç olabilir. react-dropzone, minimum geliştirme çabası ile mükemmel ve sorunsuz bir şekilde bütünleşir. Bu makale, Dropzone kütüphanesi etrafında mükemmel bir sarmalayıcı olan react-dropzone paketini kullanarak bir React uygulamasıyla Dropzone'u entegre etmeniz için size rehberlik edecektir.

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

Neden React'te Dropzone Kullanılmalı?

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çimini etkinleştirmek için dosyaları sürükleyip bırakmasına izin verir ve programlı olarak bir dosya iletişim kutusu ekler.

2. Önizlemeler

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

3. Çoklu Dosya Yüklemeleri

Aynı anda birden fazla dosya yüklemeyi destekler.

4. Özelleştirilebilir

Çeşitli seçenekler ve geri çağrılarla yüksek derecede özelleştirilebilir. Dosya diyalogları açılmasını veya dosya seçme iletişim kutularını özelleştirebilirsiniz.

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

Büyük dosyaları parçalı yükleme yöntemi ile yükleyin.

6. Olayları Yönetme

Dosya iletişim kutusu iptal geri çağrısı ve tarayıcı resim boyutlandırma olayları yönetilebilir.

React Uygulamasını Kurma

Dropzone'u entegre etmeden önce bir React uygulamanızın kurulu olduğundan emin olun. Eğer yoksa, bir 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 Yükleme

React projenizde Dropzone'u kullanmak için react-dropzone paketini yüklemeniz gerekiyor:

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ı

React bileşeninde react-dropzone kullanmanın basit bir örneği burada:

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. Daha sonra dosyaları ele alabilir, örneğin bir sunucuya yükleyebilirsiniz. Dosyaları fetch kullanarak yüklemek için onDrop geri çağrısını şu şekilde genişletebilirsiniz:

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

Yüklenen dosyaların önizlemelerini de gösterebilirsiniz. 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

Temizleme

Bellek sızıntılarını önlemek için nesne URL'lerini iptal etmek önemlidir. Bunu useEffect hook'unu kullanarak başarabilirsiniz:

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'i Tanıtma

IronPDF, Node.js uygulamaları içinde PDF oluşturmayı kolaylaştırmak için tasarlanmış güçlü bir npm paketidir. HTML içerikten, URL'lerden veya hatta mevcut PDF dosyalarından PDF belgeleri oluşturmanızı sağlar. İster fatura, rapor veya başka tür bir belge oluşturun, IronPDF süreci sezgisel API'si ve sağlam özellik seti ile basitleştirir.

IronPDF'in temel özellikleri arasında şunlar yer alır

1. HTML'den PDF'e Dönüştürme

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

2. URL'den PDF'e Dönüştürme

URL'lerden doğrudan PDF oluşturun. Bu, web sayfalarının içeriğini yakalamanız ve programlı olarak PDF dosyaları olarak kaydetmenizi sağlar.

3. PDF Manipülasyonu

Mevcut PDF belgelerini kolayca birleştirin, ayırın ve yönetin. IronPDF, PDF dosyalarını manipüle etmek için sayfa ekleme, belgeleri bölme ve daha fazlası gibi işlevsellikler sağlar.

4. PDF Güvenliği

PDF belgelerinizi şifrelerle şifreleyerek veya dijital imzalar uygulayarak güvence altına alın. IronPDF, hassas belgelerinizi yetkisiz erişimden korumak için seçenekler sunar.

5. Yüksek Kaliteli Çıktı

Metin, resim ve biçimlendirmenin hassas bir şekilde işlendiği yüksek kaliteli PDF belgeleri üretin. IronPDF, oluşturulan PDF'lerin orijinal içeriği korumasını sağlar.

6. Çapraz Platform Uyumluluğu

IronPDF, Windows, Linux ve macOS dahil olmak üzere çeşitli platformlarla uyumludur, bu da onu geniş bir geliştirme ortamı yelpazesi için uygun kılar.

7. Basit Entegrasyon

IronPDF'i npm paketi ile Node.js uygulamalarınıza kolayca entegre edin. API iyi belgelenmiştir, bu da projelerinize PDF oluşturma yeteneklerini kolayca eklemenizi sağlar.

İster bir web uygulaması, ister sunucu tarafı bir script veya komut satırı aracı oluşturun, IronPDF sizi profesyonel kalitede PDF belgeleri kolay ve güvenilir bir şekilde yaratmanız için yetkilendirir.

IronPDF kullanarak PDF Belgesi oluştur ve Dropzone NPM paketini kullan

Bağımlılıkları Yükleyin: İlk önce, aşağıdaki komutu kullanarak yeni bir Next.js projesi oluşturun (zaten yapmadıysanız): Kurulum için sayfayı inceleyin.

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

Sonra, proje dizininize gidin:

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

Gerekli paketleri yükleyin:

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

Bir PDF Oluştur: Şimdi, IronPDF kullanarak PDF oluşturmanın basit bir örneğini yapalım. Next.js bileşeninizde (örneğin, 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 yalnızca Node üzerinde çalıştığı için, bir sonraki adımda PDF'nin oluşturulduğu uygulama için node üzerinde bir API ekleyin.

Bir dosya pdf.js oluşturun pages/api klasorunde ve asagidaki kaynak kodunu ekleyin:

// 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, PDF oluşturmak için web sitesi URL'sini girin ve "PDF Oluştur" üzerine tıklayın. Asagida gösterildigi gibi awesomeIron.pdf adli bir dosya indirilecek.

Simdi Dropezone'a tiklayin ve indirilen dosyayi secin. Bu, dosyanin adinin altta gösterildigi bir onizlemesini gösterecektir: awesomeIron.pdf.

IronPDF Lisansı

Lisans detayları için IronPDF sayfasına bakın.

Aşağıda gösterildiği gibi uygulamada Lisans Anahtarını 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 entegrasyonunu react-dropzone kullanarak React ile yapmak, dosya yükleme deneyimini önemli ölçüde artıran basit bir süreçtir. Sürükle ve bırak gibi özellikler, dosya önizlemeleri ve kapsamlı özelleştirme seçenekleri sayesinde react-dropzone, React projelerinize değerli bir katkı olabilir. [1] Uygulamanızın ihtiyaçlarını karşılamak için onun yeteneklerini keşfetmeye ve özelleştirmeye başlayın!

[2] IronPDF, diğer yandan, uygulamalara kolayca entegre edilebilen çok yönlü bir PDF oluşturma ve düzenleme kütüphanesidir. [3] IronPDF, geliştiricilerin başlamasına yardımcı olması için kapsamlı dökümantasyon ve kod örnekleri sunar.

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

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

Darrius Serrant, Miami Üniversitesi'nden Bilgisayar Bilimleri lisans derecesine sahiptir ve Iron Software'de Tam Yığın WebOps Pazarlama Mühendisi olarak çalışmaktadır. Küçük yaşlardan itibaren kodlamaya ilgi duyan Darrius, bilişimi hem gizemli hem de erişilebilir buldu ve onu yaratıcılık ve problem çö...

Daha Fazlasını Oku

Iron Destek Ekibi

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