### Install developer dependencies with pnpm install Source: https://github.com/enyo/dropzone/blob/main/CONTRIBUTING.md Installs all developer dependencies needed to compile source files and test the library. ```bash $ pnpm install ``` -------------------------------- ### Install and run development commands with pnpm Source: https://github.com/enyo/dropzone/blob/main/README.md Use these pnpm commands to install dependencies and run the library's unit tests, browser tests, and local development servers for the documentation and website. ```bash pnpm install pnpm build # the library and the docs pnpm test # the library's unit tests pnpm test:e2e # the library's browser tests pnpm dev:docs # the documentation, locally pnpm dev:website # the website, locally ``` -------------------------------- ### Install Dropzone with npm or pnpm Source: https://github.com/enyo/dropzone/blob/main/packages/dropzone/README.md Install the Dropzone package using npm or pnpm. The command shows both options. ```bash npm install dropzone # or pnpm add dropzone ``` -------------------------------- ### Build the deployable site with pnpm build:site Source: https://github.com/enyo/dropzone/blob/main/README.md Run this command to build the website and documentation together into the '_site/' directory. CI runs the same script, so the local output matches what gets deployed. ```bash pnpm build:site ``` -------------------------------- ### Install Dropzone with pnpm Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/installation/package-manager.md Use pnpm to add Dropzone to your project. Run this command in your project directory. ```bash $ pnpm add dropzone ``` -------------------------------- ### Run the website development server Source: https://github.com/enyo/dropzone/blob/main/apps/website/README.md Start the development server for the website. The first command runs from the repository root, and the second uses the pnpm filter to run the dev script for the @dropzone/website package, opening the browser. ```bash pnpm dev:website # from the repository root pnpm --filter @dropzone/website run dev -- --open ``` -------------------------------- ### Display existing files from server with displayExistingFile Source: https://github.com/enyo/dropzone/wiki/FAQ Use displayExistingFile to show files already stored on the server. The example covers resizing in the browser, using a pre-sized thumbnail, and adjusting maxFiles based on the number of files already on the server. ```js Dropzone.options.myDropzone = { init: function() { let myDropzone = this; // If you only have access to the original image sizes on your server, // and want to resize them in the browser: let mockFile = { name: "Filename 2", size: 12345 }; myDropzone.displayExistingFile(mockFile, "https://i.picsum.photos/id/959/600/600.jpg"); // If the thumbnail is already in the right size on your server: let mockFile = { name: "Filename", size: 12345 }; let callback = null; // Optional callback when it's done let crossOrigin = null; // Added to the `img` tag for crossOrigin handling let resizeThumbnail = false; // Tells Dropzone whether it should resize the image first myDropzone.displayExistingFile(mockFile, "https://i.picsum.photos/id/959/120/120.jpg", callback, crossOrigin, resizeThumbnail); // If you use the maxFiles option, make sure you adjust it to the // correct amount: let fileCountOnServer = 2; // The number of files already uploaded myDropzone.options.maxFiles = myDropzone.options.maxFiles - fileCountOnServer; } }; ``` -------------------------------- ### Register event handler with init config Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/events.md For declarative setups, use the init config function to access the Dropzone instance. Use the function() syntax to bind 'this' to the instance. ```javascript Dropzone.options.myElement = { // Note: using "function()" here to bind `this` to // the Dropzone instance. init: function() { this.on("addedfile", file => { console.log("A file has been added"); }); } }; ``` -------------------------------- ### Chunk object example for chunked uploads Source: https://github.com/enyo/dropzone/wiki/FAQ Example of the chunk object passed to the params callback when chunking is enabled. It contains the file, index, status, and progress of the current chunk. ```javascript var chunk = { file: file, index: 0, status: Dropzone.UPLOADING, progress: 0.4 } ``` -------------------------------- ### Build and run end-to-end tests with pnpm build and pnpm test:e2e Source: https://github.com/enyo/dropzone/blob/main/CONTRIBUTING.md Builds the library first, then runs end-to-end tests that drive the built files through a real browser. Playwright starts and stops the test server automatically. ```bash $ pnpm build ``` ```bash $ pnpm test:e2e ``` -------------------------------- ### Handle server response with success event in Dropzone Source: https://github.com/enyo/dropzone/wiki/FAQ Use the success event to access the responseText from the server. The example appends the response text to the preview element. ```js Dropzone.options.myDropzone = { init: function() { this.on("success", function(file, responseText) { // Handle the responseText here. For example, add the text to the preview element: file.previewTemplate.appendChild(document.createTextNode(responseText)); }); } }; ``` -------------------------------- ### Set Dropzone URL dynamically with processing event Source: https://github.com/enyo/dropzone/wiki/Set-URL-dynamically Use the 'processing' event to change the URL for each file upload. The example sets options.url to '/some-other-url' when a file is processed. ```html
``` -------------------------------- ### Provide default thumbnail for non-image files Source: https://github.com/enyo/dropzone/wiki/FAQ Emit the thumbnail event for files that are not images to set a default thumbnail. The example checks the file type and emits a thumbnail with a URL. ```js myDropzone.on("addedfile", function(file) { if (!file.type.match(/image.*/)) { // This is not an image, so Dropzone doesn't create a thumbnail. // Set a default thumbnail: myDropzone.emit("thumbnail", file, "http://path/to/image"); // You could of course generate another image yourself here, // and set it as a data url. } }); ``` -------------------------------- ### AWS S3 Multipart Upload with Dropzone Source: https://github.com/enyo/dropzone/blob/main/packages/dropzone/test/test-sites/2-integrations/aws-s3-multipart.html Complete example for implementing Amazon S3 multipart upload with Dropzone. The S3 object contains placeholder functions that must be replaced with real AWS requests: getUploadId returns a demo ID, getUploadUrl constructs the upload URL, and completeMultipartUpload sends a POST to /amazon-complete. The Dropzone configuration uses chunking with a 100KB chunk size, retries up to 3 times, and disables parallel uploads. On success, it extracts ETags from response headers and completes the multipart upload. ```javascript // This follows the instructions for multipart upload as described here: // https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html // // If you want to implement an Amazon S3 Multi Part Upload on your website as // well, you can copy the code below but you need to make a few adjustments to // the S3 object that contains the functions. // // The Dropzone configuration can be used as is. // An object that groups all S3 related functionality. const S3 = { // This needs to make a request to AWS S3 to get an actual upload ID. Please // refer to the AWS docs for more info. // See https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html#API_CreateMultipartUpload_ResponseElements getUploadId: async () => "demo-id", // This needs to be implemented so it returns the correct AWS upload URL that // includes your key. // See https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html getUploadUrl: (uploadId, partNumber) => `/amazon-multipart-upload?uploadId=${uploadId}&partNumber=${partNumber}`, // A demo implementation that completes the multipart upload. // See: https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html completeMultipartUpload: async (uploadId, parts) => { let data = { UploadId: uploadId, MultipartUpload: { Parts: parts.map((part) => ({ PartNumber: part.number, ETag: part.etag, })), }, }; // Issue the http request. await fetch(`/amazon-complete`, { method: "POST", body: JSON.stringify(data), }); }, }; // The Dropzone configuration: (async () => { const uploadId = await S3.getUploadId(); new Dropzone(".dropzone", { method: "PUT", url: (_, dataBlocks) => S3.getUploadUrl(uploadId, dataBlocks[0].chunkIndex + 1), init: function () { this.on("success", async (file) => { // Get the etag from the individual headers: const parts = file.upload.chunks.map((chunk) => ({ number: chunk.index + 1, etag: chunk.responseHeaders.match(/etag: "([^"]+)"/i)[1], })); // Send request to amazon to complete the multipart upload await S3.completeMultipartUpload(uploadId, parts); }); }, uploadMultiple: false, chunking: true, forceChunking: true, chunkSize: 100 * 1024, // bytes parallelChunkUploads: false, retryChunks: true, retryChunksLimit: 3, defaultHeaders: false, binaryBody: true, }); })(); ``` -------------------------------- ### Add custom remove button to file preview Source: https://github.com/enyo/dropzone/wiki/FAQ This HTML and JavaScript example shows how to create a custom remove button for each file preview. It uses the 'addedfile' event to create a button, listen for clicks, and remove the file. The button is appended to the file preview element. ```html
``` -------------------------------- ### Standalone Dropzone 6 usage with script and link tags Source: https://github.com/enyo/dropzone/blob/main/README.md Use these standalone files when not using a package manager or bundler. The script adds Dropzone as a global variable, and the CSS provides default styles. The example creates a new Dropzone instance on a div with class 'my-dropzone', posting files to '/file/post'. ```html
``` -------------------------------- ### Display server-generated image after upload with JSON response Source: https://github.com/enyo/dropzone/wiki/FAQ If the server responds with JSON containing an imageUrl, use the success event to emit a thumbnail or create a thumbnail from the URL. The JSON example shows the expected response format. ```json { "imageUrl": "http://my.image/file.jpg" } ``` ```js Dropzone.options.myDropzone = { init: function() { this.on("success", function(file, serverResponse) { // Called after the file successfully uploaded. // If the image is already a thumbnail: this.emit('thumbnail', file, serverResponse.imageUrl); // If it needs resizing: this.createThumbnailFromUrl(file, serverResponse.imageUrl); }); } }; ``` -------------------------------- ### Build the website with npm run build Source: https://github.com/enyo/dropzone/blob/main/apps/website/README.md Build the website using the static adapter. This command is run from the website directory. ```bash npm run build ``` -------------------------------- ### Typical Dropzone configuration (declarative and imperative) Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/basics/index.md Shows the typical Dropzone configuration in both declarative and imperative styles. The declarative version uses a form element with the dropzone class and sets options via Dropzone.options with the camelized id, while the imperative version imports Dropzone and calls it directly. Both configure the same options: paramName, maxFilesize, and an accept function that rejects a specific file. ```markup
``` ```javascript import Dropzone from "dropzone"; let myDropzone = Dropzone({ paramName: "file", // The name that will be used to transfer the file maxFilesize: 2, // MB accept: function(file, done) { if (file.name == "justinbieber.jpg") { done("Naha, you don't."); } else { done(); } } }); ``` -------------------------------- ### Import Dropzone and initialize with JavaScript Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/installation/package-manager.md Shows how to import Dropzone using ECMAScript modules or CommonJS, disable autoDiscover for versions before 6.0.0, and create a new Dropzone instance with an event listener. ```javascript // If you are using JavaScript/ECMAScript modules: import Dropzone from "dropzone"; // If you are using CommonJS modules: const { Dropzone } = require("dropzone"); // If you are using an older version than Dropzone 6.0.0, // then you need to disabled the autoDiscover behaviour here: Dropzone.autoDiscover = false; let myDropzone = new Dropzone("#my-form"); myDropzone.on("addedfile", file => { console.log(`File added: ${file.name}`); }); ``` -------------------------------- ### Dropzone.js configuration and upload simulation JavaScript Source: https://github.com/enyo/dropzone/blob/main/apps/website/static/bootstrap.html JavaScript to set up a Dropzone instance on the body, configure previews, and simulate file uploads with progress events. Includes event handlers for adding files, updating progress, and managing the queue. ```javascript // Get the template HTML and remove it from the doument var previewNode = document.querySelector("#template"); previewNode.id = ""; var previewTemplate = previewNode.parentNode.innerHTML; previewNode.parentNode.removeChild(previewNode); var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone url: "http://www.the-url-you-want-to-use.com/dropzone.php", // Set the url thumbnailWidth: 80, thumbnailHeight: 80, parallelUploads: 20, previewTemplate: previewTemplate, autoQueue: false, // Make sure the files aren't queued until manually added previewsContainer: "#previews", // Define the container to display the previews clickable: ".fileinput-button" // Define the element that should be used as click trigger to select files. }); myDropzone.on("addedfile", function (file) { // Hookup the start button file.previewElement.querySelector(".start").onclick = function () { myDropzone.enqueueFile(file); }; }); // Update the total progress bar myDropzone.on("totaluploadprogress", function (progress) { document.querySelector("#total-progress .progress-bar").style.width = progress + "%"; }); myDropzone.on("sending", function (file) { console.log("hi"); // Show the total progress bar when upload starts document.querySelector("#total-progress").style.opacity = "1"; // And disable the start button file.previewElement.querySelector(".start").setAttribute("disabled", "disabled"); }); // Hide the total progress bar when nothing's uploading anymore myDropzone.on("queuecomplete", function (progress) { document.querySelector("#total-progress").style.opacity = "0"; }); // Setup the buttons for all transfers // The "add files" button doesn't need to be setup because the config // `clickable` has already been specified. document.querySelector("#actions .start").onclick = function () { myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED)); }; document.querySelector("#actions .cancel").onclick = function () { myDropzone.removeAllFiles(true); }; // Now fake the file upload, since GitHub does not handle file uploads // and returns a 404 var minSteps = 6, maxSteps = 60, timeBetweenSteps = 100, bytesPerStep = 100000; myDropzone.uploadFiles = function (files) { var self = this; for (var i = 0; i < files.length; i++) { var file = files[i]; totalSteps = Math.round( Math.min(maxSteps, Math.max(minSteps, file.size / bytesPerStep)), ); self.emit("sending", file); for (var step = 0; step < totalSteps; step++) { var duration = timeBetweenSteps * (step + 1); setTimeout( (function (file, totalSteps, step) { return function () { file.upload = { progress: (100 * (step + 1)) / totalSteps, total: file.size, bytesSent: ((step + 1) * file.size) / totalSteps, }; self.emit("uploadprogress", file, file.upload.progress, file.upload.bytesSent); if (file.upload.progress == 100) { file.status = Dropzone.SUCCESS; self.emit("success", file, "success", null); self.emit("complete", file); self.processQueue(); } }; })(file, totalSteps, step), duration, ); } } }; ``` -------------------------------- ### Create a Dropzone instance Source: https://github.com/enyo/dropzone/blob/main/packages/dropzone/README.md Import the Dropzone class and create a new instance targeting an HTML element with the given selector and URL for file uploads. ```js import { Dropzone } from "dropzone"; const dropzone = new Dropzone("div#myId", { url: "/file/post" }); ``` -------------------------------- ### Include Dropzone v6 beta via unpkg Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/installation/stand-alone.md Opt into Dropzone v6 beta, which is lighter (46kB vs 115kB) but drops Internet Explorer support. Check the CHANGELOG for breaking changes. ```html ``` -------------------------------- ### Run unit tests with pnpm test Source: https://github.com/enyo/dropzone/blob/main/CONTRIBUTING.md Runs unit tests against the src/ directory in a real browser using Vitest. ```bash $ pnpm test ``` -------------------------------- ### Dropzone.js CSS for table-like preview and progress styling Source: https://github.com/enyo/dropzone/blob/main/apps/website/static/bootstrap.html CSS to style the dropzone previews as a table, hide/show progress and action buttons based on upload state, and animate the total progress bar. Apply this to match the demo's appearance. ```css html, body { height: 100%; } #actions { margin: 2em 0; } .progress { width: 10rem; } /* Mimic table appearance */ div.table { display: table; } div.table .file-row { display: table-row; } div.table .file-row > div { display: table-cell; vertical-align: top; border-top: 1px solid #ddd; padding: 8px; } div.table .file-row:nth-child(odd) { background: #f9f9f9; } /* The total progress gets shown by event listeners */ #total-progress { opacity: 0; transition: opacity 0.3s linear; } /* Hide the progress bar when finished */ #previews .file-row.dz-success .progress { opacity: 0; transition: opacity 0.3s linear; } /* Hide the delete button initially */ #previews .file-row .delete { display: none; } /* Hide the start and cancel buttons and show the delete button */ #previews .file-row.dz-success .start, #previews .file-row.dz-success .cancel { display: none; } #previews .file-row.dz-success .delete { display: block; } ``` -------------------------------- ### Include Dropzone v5 via unpkg Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/installation/stand-alone.md Link to Dropzone v5 files from unpkg. The CSS file is optional. After including these, Dropzone is available as window.Dropzone. ```html ``` -------------------------------- ### Dropzone configuration for form submission with autoProcessQueue false Source: https://github.com/enyo/dropzone/wiki/Combine-normal-form-with-Dropzone Configures Dropzone with autoProcessQueue: false, uploadMultiple: true, parallelUploads: 100, and maxFiles: 100. The init function adds a click listener to the submit button to process the queue, and defines event handlers for sendingmultiple, successmultiple, and errormultiple. ```javascript Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element // The configuration we've talked about above autoProcessQueue: false, uploadMultiple: true, parallelUploads: 100, maxFiles: 100, // The setting up of the dropzone init: function() { var myDropzone = this; // First change the button to actually tell Dropzone to process the queue. this.element.querySelector("button[type=submit]").addEventListener("click", function(e) { // Make sure that the form isn't actually being sent. e.preventDefault(); e.stopPropagation(); myDropzone.processQueue(); }); // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead // of the sending event because uploadMultiple is set to true. this.on("sendingmultiple", function() { // Gets triggered when the form is actually being sent. // Hide the success button or the complete form. }); this.on("successmultiple", function(files, response) { // Gets triggered when the files have successfully been sent. // Redirect user or notify of success. }); this.on("errormultiple", function(files, response) { // Gets triggered when there was an error sending the files. // Maybe show form again, and notify user of error }); } } ``` -------------------------------- ### Equivalent HTML file input Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/setup/declarative.md Shows the equivalent HTML input that Dropzone would handle. The uploaded files are handled as if this input were present. ```markup ``` -------------------------------- ### Configure Dropzone with Dropzone.options Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/setup/declarative.md Sets configuration options for a Dropzone instance by using the camelized id of the form element. The script must be placed before the form in the document. ```markup
``` -------------------------------- ### Display an existing server image Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/basics/methods.md Displays an existing image from the server in the dropzone. The `callback` and `crossOrigin` parameters are optional. ```javascript // callback and crossOrigin are optional let mockFile = { name: "Filename", size: 12345 }; myDropzone.displayExistingFile(mockFile, 'https://image-url'); ``` -------------------------------- ### HTML form and button with Dropzone configuration to remove all files Source: https://github.com/enyo/dropzone/wiki/Remove-all-files-with-one-button Use this snippet to create a Dropzone form and a button that removes all files when clicked. The Dropzone is initialized with an init function that sets up an event observer on the button. The closure variable _this is used inside the observer because 'this' does not refer to the dropzone instance. To also cancel uploads, call _this.removeAllFiles(true) instead. ```html
``` -------------------------------- ### Create Dropzone imperatively with Plain JavaScript Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/setup/imperative.md Instantiates the Dropzone class with a selector and configuration object. Requires the url option when not using a form element. ```javascript // The constructor of Dropzone accepts two arguments: // // 1. The selector for the HTML element that you want to add // Dropzone to, the second // 2. An (optional) object with the configuration let myDropzone = new Dropzone("div#myId", { url: "/file/post"}); ``` -------------------------------- ### Full-page dropzone with separate clickable button and previews container Source: https://github.com/enyo/dropzone/wiki/make-the-whole-body-a-dropzone Use this HTML and JavaScript to make the entire body a dropzone. The previews container must have the 'dropzone-previews' class for correct formatting. The 'clickable' option specifies the button that triggers file selection, and 'previewsContainer' defines where previews are displayed. ```html
``` -------------------------------- ### JavaScript: Configure Dropzone to process queue on button click Source: https://github.com/enyo/dropzone/wiki/Upload-all-files-with-a-button Configures Dropzone to not auto-process files, and adds a click listener to the submit button to process the queue. Also shows how to listen for the 'addedfile' event to display the submit button. ```js Dropzone.options.myDropzone = { // Prevents Dropzone from uploading dropped files immediately autoProcessQueue: false, init: function() { var submitButton = document.querySelector("#submit-all") myDropzone = this; // closure submitButton.addEventListener("click", function() { myDropzone.processQueue(); // Tell Dropzone to process all queued files. }); // You might want to show the submit button only when // files are dropped here: this.on("addedfile", function() { // Show submit button here and/or inform user to click it. }); } }; ``` -------------------------------- ### TypeScript usage with Dropzone Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/installation/package-manager.md Import Dropzone and DropzoneOptions types, create a dropzone with options, and add an event listener with inferred argument types. ```typescript import { Dropzone } from "dropzone"; import type { DropzoneOptions } from "dropzone"; const options: DropzoneOptions = { url: "/file/post", maxFilesize: 10 }; const dropzone = new Dropzone("div#myId", options); // The listener's arguments are inferred from the event name. dropzone.on("addedfile", (file) => { console.log(file.name, file.upload.progress); }); ``` -------------------------------- ### Register event handler on Dropzone instance Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/events.md Use the .on() method on a Dropzone instance to listen for events like 'addedfile'. The callback receives the file object. ```javascript let myDropzone = Dropzone("#my-element", { /* options */ }); myDropzone.on("addedfile", file => { console.log("A file has been added"); }); ``` -------------------------------- ### Use Dropzone as ES6 module Source: https://github.com/enyo/dropzone/blob/main/README.md Import Dropzone as an ES6 module and create a new instance on a div element with the specified URL. ```js import { Dropzone } from "dropzone"; const dropzone = new Dropzone("div#myId", { url: "/file/post" }); ``` -------------------------------- ### Run Playwright tests Source: https://github.com/enyo/dropzone/blob/main/apps/website/README.md Run the Playwright tests for the website. The command uses pnpm filter to target the @dropzone/website package. ```bash pnpm --filter @dropzone/website run test ``` -------------------------------- ### Import Dropzone types Source: https://github.com/enyo/dropzone/blob/main/packages/dropzone/README.md Import the TypeScript types for Dropzone files and options. The types ship with the package, so no @types/dropzone is needed. ```ts import type { DropzoneFile, DropzoneOptions } from "dropzone"; ``` -------------------------------- ### Use Dropzone as CommonJS module Source: https://github.com/enyo/dropzone/blob/main/README.md Import Dropzone using CommonJS require and create a new instance on a div element with the specified URL. ```js const { Dropzone } = require("dropzone"); const dropzone = new Dropzone("div#myId", { url: "/file/post" }); ``` -------------------------------- ### Default previewTemplate HTML Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/basics/layout.md Default preview template for each file. Contains data-dz-* attributes that Dropzone updates automatically. Use this as a base when customizing the template with the previewTemplate option. ```markup
✔
✘
``` -------------------------------- ### Uninstall @types/dropzone Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/installation/package-manager.md Remove the deprecated @types/dropzone package because it describes the v5 API and will conflict with the current library. ```bash npm uninstall @types/dropzone ``` -------------------------------- ### Use body as Dropzone with separate previews container Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/misc/tips.md Instantiate Dropzone on the body element and specify a separate previews container. Set clickable to false to prevent the whole body from being clickable. ```javascript new Dropzone(document.body, { previewsContainer: ".dropzone-previews", // You probably don't want the whole body // to be clickable to select files clickable: false }); ``` -------------------------------- ### Basic Dropzone form Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/setup/declarative.md Creates a form element with the 'dropzone' class. Dropzone automatically attaches to this element and uploads dropped files to the 'action' URL. ```markup
``` -------------------------------- ### Limit number of files with maxFiles and remove rejected files Source: https://github.com/enyo/dropzone/wiki/FAQ Set the maxFiles option to limit the number of files. Register for the maxfilesexceeded event to immediately remove rejected files. ```js myDropzone.on("maxfilesexceeded", function(file) { this.removeFile(file); }); ``` -------------------------------- ### Re-enable auto discover with Dropzone.discover() Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/setup/declarative.md Adds the Dropzone.discover() call to the end of the document to manually trigger auto discovery, which was removed in version 6.0.0. ```html ``` -------------------------------- ### HTML form markup for Dropzone with previews and input fields Source: https://github.com/enyo/dropzone/wiki/Combine-normal-form-with-Dropzone The form element with id 'my-awesome-dropzone' and class 'dropzone'. It includes a previews container and input fields for email and password, plus a submit button. Dropzone automatically submits all input fields inside the form. ```html
``` -------------------------------- ### Custom Dropzone with overridden event handlers Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/theming.md Overrides Dropzone's default event handlers to completely customize the UI. Use only when you don't need the default Dropzone UI and are interested in event handlers, file upload, and drag'n'drop functionality. The `previewTemplate` is set from an existing element's innerHTML, and each event handler (e.g., `addedfile`, `thumbnail`, `uploadprogress`) is replaced with a custom implementation. ```javascript // This is an example of completely disabling Dropzone's default behavior. // Do *not* use this unless you really know what you are doing. Dropzone.myDropzone.options = { previewTemplate: document.querySelector('#template-container').innerHTML, // Specifing an event as an configuration option overwrites the default // `addedfile` event handler. addedfile: function(file) { file.previewElement = Dropzone.createElement(this.options.previewTemplate); // Now attach this new element some where in your page }, thumbnail: function(file, dataUrl) { // Display the image in your file.previewElement }, uploadprogress: function(file, progress, bytesSent) { // Display the progress } // etc... }; ``` -------------------------------- ### Remove file on preview click with 'addedfile' event Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/misc/tips.md Listen for the 'addedfile' event to attach a click handler to the file's preview element, allowing removal of the file when clicked. ```javascript myDropzone.on("addedfile", function(file) { file.previewElement.addEventListener("click", function() { myDropzone.removeFile(file); }); }); ``` -------------------------------- ### Create Dropzone imperatively with jQuery Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/setup/imperative.md Uses the dropzone method added to jQuery elements, accepting an optional configuration object. Requires the url option when not using a form element. ```javascript // The dropzone method is added to jQuery elements and can // be invoked with an (optional) configuration object. $("div#myId").dropzone({ url: "/file/post" }); ``` -------------------------------- ### Standard HTML file upload form Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/setup/server-side-implementation.md Standard HTML form that demonstrates how files are uploaded to the server. Dropzone uses the same multipart/form-data encoding, so any server that accepts this form will accept Dropzone uploads. ```markup
``` -------------------------------- ### HTML: Submit button and Dropzone form Source: https://github.com/enyo/dropzone/wiki/Upload-all-files-with-a-button Defines the submit button and the Dropzone form. The form has an action of '/target' and an id of 'my-dropzone'. ```html
``` -------------------------------- ### HTML form element for Dropzone Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/installation/package-manager.md Create a form element with the class 'dropzone' that Dropzone will take over. This is the target element for the dropzone. ```markup
``` -------------------------------- ### Reject images based on image dimensions Source: https://github.com/enyo/dropzone/wiki/FAQ Reject images based on dimensions by waiting for the thumbnail event. The accept callback is stored on the file object so it can be called later with an error message when dimensions exceed the limits. ```javascript var maxImageWidth = 800, maxImageHeight = 800; Dropzone.options.myDropzone = { // Make sure only images are accepted acceptedFiles: "image/*", init: function() { // Register for the thumbnail callback. // When the thumbnail is created the image dimensions are set. this.on("thumbnail", function(file) { // Do the dimension checks you want to do if (file.width > maxImageWidth || file.height > maxImageHeight) { file.rejectDimensions() } else { file.acceptDimensions(); } }); }, // Instead of directly accepting / rejecting the file, setup two // functions on the file that can be called later to accept / reject // the file. accept: function(file, done) { file.acceptDimensions = done; file.rejectDimensions = function() { done("Invalid dimension."); }; // Of course you could also just put the `done` function in the file // and call it either with or without error in the `thumbnail` event // callback, but I think that this is cleaner. } }; ``` -------------------------------- ### Override Dropzone.confirm Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/basics/methods.md Overrides the default browser confirm modal. The `rejected` callback may be undefined, so handle that case. ```javascript Dropzone.confirm = function(question, accepted, rejected) { // Ask the question, and call accepted() or rejected() accordingly. // CAREFUL: rejected might not be defined. Do nothing in that case. }; ``` -------------------------------- ### Override thumbnail event listener in Dropzone configuration Source: https://github.com/enyo/dropzone/wiki/How-to-theme-Dropzone Use this when you change previewTemplate to remove the element, because the default thumbnail listener will fail. The new listener receives the file and dataUrl, allowing custom handling of the thumbnail data. ```javascript new Dropzone("#drop", { thumbnail: function(file, dataUrl) { /* do something else with the dataUrl */ } }); ``` -------------------------------- ### Custom remove link with data-dz-remove Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/basics/layout.md Add this element inside the previewTemplate to enable a custom remove button. Clicking it removes the file, similar to the built-in addRemoveLinks option. ```markup Click me to remove the file. ``` -------------------------------- ### HTML fallback form with file input Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/getting-started/setup/fallback-for-no-javascript.md Define a fallback element inside the dropzone form. When Dropzone initializes, it removes this element. If JavaScript is disabled, the user sees the file input and can upload files without drag and drop. ```markup
``` -------------------------------- ### Add file-specific data to upload with 'sending' event Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/misc/tips.md Register a handler for the 'sending' event to append file-specific data to the POST request. The formData object is provided by Dropzone and is sent with the upload. ```javascript myDropzone.on("sending", function(file, xhr, formData) { // Will send the filesize along with the file as POST data. formData.append("filesize", file.size); }); ``` -------------------------------- ### Override default addedfile event handler in Dropzone Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/basics/index.md Overrides the default addedfile event handler by passing it as an option to Dropzone. This replaces the default behavior instead of adding a new listener with myDropzone.on("addedfile", ...). The documentation warns that this should only be done with extreme caution as it can break on library upgrades and remove default functionality. ```javascript let myDropzone = Dropzone("#my-element", { addedfile: file => { // ONLY DO THIS IF YOU KNOW WHAT YOU'RE DOING! } }); ``` -------------------------------- ### Remove a file on upload complete Source: https://github.com/enyo/dropzone/blob/main/apps/docs/docs/configuration/basics/methods.md Automatically removes a file from the dropzone when its upload completes. The `removedfile` event is triggered by `removeFile(file)`. ```javascript myDropzone.on("complete", function(file) { myDropzone.removeFile(file); }); ``` -------------------------------- ### Disable autoDiscover globally Source: https://github.com/enyo/dropzone/wiki/FAQ Set Dropzone.autoDiscover to false to prevent Dropzone from automatically scanning the document for elements with the 'dropzone' class. This avoids the 'Dropzone already attached.' error when creating instances programmatically. ```javascript Dropzone.autoDiscover = false; ``` -------------------------------- ### Disable autoDiscover for a specific element Source: https://github.com/enyo/dropzone/wiki/FAQ Set Dropzone.options.myAwesomeDropzone to false to disable autoDiscover for a specific element with the id 'myAwesomeDropzone'. This prevents the 'Dropzone already attached.' error for that element. ```javascript Dropzone.options.myAwesomeDropzone = false; ``` -------------------------------- ### Submit additional data with hidden input fields in Dropzone form Source: https://github.com/enyo/dropzone/wiki/FAQ When the Dropzone element is a
, all hidden input fields are automatically submitted as POST data. The fallback div is removed if not needed. ```html
etc...
``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.