Upload your existing image files to Dropzone

I have implemented image upload functionality using Dropzonejs in a form. To handle multiple form fields, I have set autoProcessQueue to false and processing it on click of the Submit button as shown below.

Dropzone.options.portfolioForm = { 

    url: "/user/portfolio/save",
    previewsContainer: ".dropzone-previews",
    uploadMultiple: true,
    parallelUploads: 8,
    autoProcessQueue: false,
    autoDiscover: false,
    addRemoveLinks: true,
    maxFiles: 8,

    init: function() {

         var myDropzone = this;
         this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {

             e.preventDefault();
             e.stopPropagation();
             myDropzone.processQueue();
         });
     }
 }

While this functionality works well for uploading images, I also want to display previously uploaded images when the form is edited. I found a helpful resource in the Dropzone Wiki that explains how to show existing files stored on the server: https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-files-already-stored-on-server

Although this method populates the dropzone-preview area with existing images, it does not include these images in the form submit. I believe this is because the images are not added to the queue. In this case, how can I handle updates on the server side if a user removes an existing image?

Additionally, what would be the preferred approach: adding previously uploaded images to the queue again or simply sending information about the removed file?

Answer №1

After struggling to add images for a while, I decided to send information about the deleted images back to the server instead.

When loading existing images into dropzone, I link the image's URL to the mockFile object. In the removedfile event, I add a hidden input to the form if the file being removed is a prepopulated image (which is determined by checking if the file passed into the event has a URL property). Here is the relevant code snippet:

Dropzone.options.imageDropzone = {
    paramName: 'NewImages',
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    maxFiles: 100,
    init: function () {
        var myDropzone = this;

        // Populate any existing thumbnails
        if (thumbnailUrls) {
            for (var i = 0; i < thumbnailUrls.length; i++) {
                var mockFile = { 
                    name: "myimage.jpg", 
                    size: 12345, 
                    type: 'image/jpeg', 
                    status: Dropzone.ADDED, 
                    url: thumbnailUrls[i] 
                };

                // Call the default addedfile event handler
                myDropzone.emit("addedfile", mockFile);

                // And optionally show the thumbnail of the file:
                myDropzone.emit("thumbnail", mockFile, thumbnailUrls[i]);

                myDropzone.files.push(mockFile);
            }
        }

        this.on("removedfile", function (file) {
            // Only files that have been programmatically added should
            // have a URL property.
            if (file.url && file.url.trim().length > 0) {
                $("<input type='hidden'>").attr({
                    id: 'DeletedImageUrls',
                    name: 'DeletedImageUrls'
                }).val(file.url).appendTo('#image-form');
            }
        });
    }
});

Server-side code (ASP MVC controller):

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        foreach (var url in viewModel.DeletedImageUrls)
        {
            // Code to remove the image
        }

        foreach (var image in viewModel.NewImages)
        {
            // Code to add the image
        }
    }
}

Hopefully, this explanation clarifies things.

Answer №2

Building on the insights shared by Teppic, I discovered that triggering the complete event was necessary in order to remove the progress bar from the preview.

var data = {
    title: info.title,
    size: info.size,
    status: Dropzone.ADDED,
    isValid: true
};
myUploader.emit("itemadded", data);                                
myUploader.emit("thumbnailcreated", data, info.link);
myUploader.emit("processcompleted", data);
myUploader.items.push(data);

Answer №4

If you're looking for more information, check out the official FAQ by clicking here.

Answer №5

Utilizing the dropzone's built-in "displayExistingFile" method was the key to solving this problem.

Within your initialization function, follow these steps:

  1. Create a mock file with the following properties: name, size, and dataURL.

  2. Invoke the displayExistingFile function with the mock file as a parameter.

Instead of using 'null', consider providing a callback function to handle the thumbnail load event.

The use of 'anonymous' is necessary for setting the cross-origin property.

Answer №6

Originally, my intention was to programmatically upload an existing file using the following code:

myDropzone.emit("addedfile", imageFile);                                
myDropzone.emit("thumbnail", imageFile, imageUrl);
myDropzone.files.push(file);

However, after reading through this discussion on Dropzone's Github, I discovered a simpler way to upload directly:

myDropzone.uploadFiles([imageFile])

Surprisingly, the uploadFiles method is not mentioned in the Dropzone Documentation. I wanted to share this insight with other Dropzone users.

Hopefully, this information proves to be helpful to someone.

Answer №7

If you possess the file's URL, you have the ability to include the file utilizing the addFile function.

fetch("fileUrl")
    .then(response => response.blob())
    .then((blob) => {
        const newFile = new File([blob], "newFileName.jpg", {
            type: blob.type,
        });
        myDropzone.addFile(newFile);
    });

Answer №8

When the upload files button is clicked, the dropzone will be cleared of all files. You have the option to either clear all files at once using removeAllFiles(), or to delete a specific file by using removeFile(fileName).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

vue implementing autoscroll for long lists

I am looking to implement an autoscrolling log feature on my webpage that is dynamically fetched from a REST endpoint. To handle the potentially large size of this log, I decided to use vue-virtual-scroll-list. Additionally, I wanted the log to automatical ...

Lack of element content in AngularJS unit testing

I am currently working with AngularJS 1.5+, jasmine, and karma, and I am facing an issue when testing a component along with its template. When the component's template is compiled, it seems to be missing the expected content. Here is a snippet of th ...

Converting HTML Javascript to JAVA with the help of Selenium

Can someone help me extract the value of h1 as a string using selenium? Check out the HTML javascript snippet below- <script type="text/javascript"> $(window).load(function() { var $windowHeight = $(window).height() -12; $(" ...

Transform the character encoding from a non-standard format to UTF-8

Imagine a scenario where there is a page with <meta charset="EUC-KR">, let's call it address-search.foo.com, that allows users to search for an address and sends the data to a specified URL by submitting an HTML form using the POST met ...

"I am eager to showcase the text upon pressing the Enter key, implementing an Immediately Invoked Function Expression

My input text box is supposed to store and display the output in an unordered list format when I hit enter. The function works fine without IIFE using onclick event, but it's not working with IIFE. Can anyone assist me with this issue? <html> ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

What is the best way to reference a component from another component in a React application?

I've been utilizing the react-notification-system library in my project, and here's a snippet of how I've incorporated it into my code. import React from 'react'; import Notification from 'react-notification-system'; cl ...

Learn how to pull values from a single JsonNode into multiple beans within a Play Framework controller

In my Java project using Play Framework, I am working with jQuery Ajax to post data in the form of a String representation of JsonNode. When writing an action method in my controller class to handle this Ajax call, I encountered an issue. The data being s ...

Prepare yourself for the possibility of receiving a caution while within a try-catch block

After implementing the MongoClient.connect method and encountering the warning 'await' has no effect on the type of this expression, it became clear that including the .catch line immediately following (which is currently commented out) mitigated ...

Issue with AJAX show/hide causing scrolling to top

I've implemented ajax show hide functionality to display tabs, but whenever I scroll down to the tab and click on it, the page scrolls back to the top. You can check out the example code in this fiddle: http://jsfiddle.net/8dDat/1/ I've attempt ...

An error of type TypeError occurred while attempting to browserify a module in a Node.js environment

Is there a way to integrate this algorithm into a client-side function? I'm looking to use the RAKE Module within a browserified function on the client side. You can find the RAKE Module on GitHub here: https://github.com/waseem18/node-rake To compi ...

Tips on obtaining checkbox value in an AJAX request

I need to retrieve the value of a checkbox using Ajax in order to store it as a user preference in the database. This task is new to me, and I'm feeling a bit overwhelmed. Here is my JavaScript file: $(document).ready(function() { E.accounts.chang ...

Struggling to make dynamically created SVG 'use' elements function properly

SVG offers a unique system with symbol and use where icons can be defined once and reused throughout the SVG using use. However, I am having trouble getting it to work from JavaScript. You can view an example on this JSFiddle link. When programmatically ...

What is the code for displaying and concealing the "add to cart" button using PHP

I am modifying my addtocart.phtml file on my Magento website. My goal is to use PHP code to hide or show the add to cart button based on the product's category. Here is what I have in mind: <?php if($_product_category == "beds"){ <div class ...

Dealing with an Incorrect Date in JavaScript

After working on a JavaScript logic to extract date and time from certain values, I realized that my approach needed some adjustments. Initially, I parsed the DateTime and converted it to a string. Then, I split the string to retrieve the date component. ...

What is the process for configuring CORS settings in Azure Blob Storage through the Portal?

Our Windows Azure platform is equipped with a blob storage system. http://mytest.blob.core.windows.net/forms Using CloudBerry, I have uploaded various files to the storage which can be successfully downloaded via web browsers. These files are simple text ...

Placing the word "repeatedly" in a d3 js tree

I am currently working on building a tree structure and incorporating edge labels. The tree allows nodes to be dynamically added using a plus button that appears when you click on a parent node. One issue arises when adding a new child. (apologies for the ...

What causes a stack trace to be logged alongside a rejected Promise in Node version 7.2.0?

After executing this code in Node 7.2.0: let prms = Promise.reject(new Error('error')); prms.catch(() => {}); console.log(prms); I anticipated Promise {<rejected> Error: error} to be displayed on the console, however I was instead pre ...

Grid Column with Checkboxes in Kendo UI for Vue

Seeking help in adding a checkbox column to a Kendo UI Vue grid. The column should display the values of a boolean field from the grid's data source. While I am aware of how to add a checkbox column for selection as demonstrated here: https://www.tele ...

Maximizing the potential of typescript generics in Reactjs functional components

I have a component within my react project that looks like this: import "./styles.css"; type InputType = "input" | "textarea"; interface ContainerProps { name: string; placeholder: string; as: InputType; } const Conta ...