10

I am using dropzone.js. When I try to delete files only the thumbnails get deleted but not the files from server. I tried some ways but it just gives me the name of the image which was on client side and not the name on server side(both names are different, storing names in encrypted form).

Any help would be much appreciated..

Grish
  • 832
  • 2
  • 10
  • 23
  • you might to post some code here, especially on the backend side where you actually process the files. so we can tell what is actually going on – Fikri Marhan Jul 03 '13 at 16:01
  • 1
    Please refer to [my response from the duplicate question](http://stackoverflow.com/a/17427379/170851). – enyo Jul 09 '13 at 12:26

10 Answers10

24

Another way,

Get response from your server in JSON format or a plain string (then use only response instead of response.path),

dropzone.on("success", function(file, response) {
  $(file.previewTemplate).append('<span class="server_file">'+response.path+'</span>');
});

Here, the server can return a json like this,

{
    status: 200,
    path: "/home/user/anything.txt"
}

So we are storing this path into a span that we can access when we are going to delete it.

dropzone.on("removedfile", function(file) {
  var server_file = $(file.previewTemplate).children('.server_file').text();
  alert(server_file);
  // Do a post request and pass this path and use server-side language to delete the file
  $.post("delete.php", { file_to_be_deleted: server_file } );
});

After the process, the preview template will be deleted by Dropzone along with file path stored in a span.

Harsh Vakharia
  • 2,104
  • 1
  • 23
  • 26
  • Better solution ever! on success response i have a JSON response with fileID. After success event, we underlay that ID! – Adobe Nov 11 '15 at 10:27
  • This should be the answer. Thank you! – Sam Feb 01 '16 at 19:12
  • NO! Do NOT perform deleting images on the server via `removedfile` event because when [dropzone is destroyed, it calls `removeAllFiles`](https://github.com/enyo/dropzone/blob/2df14f334aca521916433da452281a0f8616951d/src/dropzone.coffee#L730-L737) in which all images on the server will be destroyed. [Related comment](https://github.com/enyo/dropzone/issues/1399#issuecomment-258277806) – Taku Mar 16 '17 at 06:51
  • In new version change var server_file = $(file.previewTemplate).children('.server_file').text(); for var server_file = file.upload.filename; – esdebon May 29 '19 at 00:45
16

The way I handle this, is after each file is uploaded and stored on the server, I echo back the name I give the file on my server, and store it in a JS object, something like this:

PHP:

move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
echo $newFileName;

JS:

dropZone.on("success", function(file, serverFileName) {
  fileList[serverFileName] = {"serverFileName" : serverFileName, "fileName" : file.name };
});

With this, you can then write a delete script in PHP that takes in the "serverFileName" and does the actual deletion, such as:

JS:

$.ajax({
    url: "upload/delete_temp_files.php",
    type: "POST",
    data: { "fileList" : JSON.stringify(fileList) }
});

PHP:

$fileList = json_decode($_POST['fileList']);

for($i = 0; $i < sizeof($fileList); $i++)
{
    unlink(basename($fileList[$i]));
}
FunkeDope
  • 306
  • 3
  • 6
  • 3
    Tiny little problem. What if the user submits two files with the same name? Than this isn't enought.. or even worst... if he drops the same file twice to the dropzone...that's unusual, but might happen... – Nuno Gonçalves Nov 15 '13 at 12:00
  • 3
    On the PHP side, I prefix a random string using uniqid() to the filename, so even if the user uploads the same file 50 different times, I will have 50 different files and file names reported back to JS. If you want to get more advanced you can do some MD5 or hash checking, but this should be okay for most cases. – FunkeDope Nov 26 '13 at 18:42
9

Most simple way

JS file,this script will run when you click delete button

this.on("removedfile", function(file) {
alert(file.name);

$.ajax({
url: "uploads/delete.php",
type: "POST",
data: { 'name': file.name}
});


});

php file "delete.php"

<?php
$t= $_POST['name'];
echo $t;
unlink($t); 
?>
yogesh singh
  • 605
  • 6
  • 9
5

The file will be deleteed when you click the "Remove" button :

Put this on your JS file or your HTML file (or your PHP view/action file):

<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = { 
// Change following configuration below as you need there bro
autoProcessQueue: true,
uploadMultiple: true,
parallelUploads: 2,
maxFiles: 10,
maxFilesize: 5,
addRemoveLinks: true,
dictRemoveFile: "Remove",
dictDefaultMessage: "<h3 class='sbold'>Drop files here or click to upload document(s)<h3>",
acceptedFiles: ".xls,.xlsx,.doc,.docx",
//another of your configurations..and so on...and so on...
init: function() {
     this.on("removedfile", function(file) {
          alert("Delete this file?");
          $.ajax({
               url: '/delete.php?filetodelete='+file.name,
               type: "POST",
               data: { 'filetodelete': file.name}
          });
     });
}}
</script>

..and Put this code in your PHP file :

<?php
     $toDelete= $_POST['filetodelete'];
     unlink("{$_SERVER['DOCUMENT_ROOT']}/*this-is-the-folder-which-you-put-the-file-uploaded*/{$toDelete}");
     die;
?>

Hope this helps you bro :)

Raymond
  • 1,309
  • 14
  • 10
3

I've made it easier, just added new property serverFileName to the file object:

    success: function(file, response) {
        file.serverFileName = response.file_name;
    },
    removedfile: function (file, data) {
        $.ajax({
            type:'POST',
            url:'/deleteFile',
            data : {"file_name" : file.serverFileName},
            success : function (data) {
            }
        });
    }
Supervision
  • 1,683
  • 1
  • 18
  • 23
  • Thank you! This is exactly what i was looking for! In my case i need to return picture entity ID in response instead of name (path). – Zigu007 Jul 19 '22 at 11:00
2
success: function(file, serverFileName)
        {
            fileList['serverFileName'] = {"serverFileName" : serverFileName, "fileName" : file.name };

            alert(file.name);
            alert(serverFileName);
        },
        removedfile: function(file, serverFileName)
        {
            fileList['serverFileName'] = {"serverFileName" : serverFileName, "fileName" : file.name };

            alert(file.name);
            alert(serverFileName);
        }
Karthiga
  • 240
  • 3
  • 4
  • 10
  • Which URL does the "removedfile" event send request to? – naneri Jun 29 '15 at 08:46
  • also, how do I extend instead of overriding the default behaviour of that event? Because if I override it - the thumbnail of the image is still on the page and I want it to dissapear as well. – naneri Jun 29 '15 at 09:08
2

When you save the image in upload from there you have to return new file name :

echo json_encode(array("Filename" => "New File Name"));

And in dropzone.js file :

success: function(file,response) {

    obj = JSON.parse(response);

    file.previewElement.id = obj.Filename;
    if (file.previewElement) {
      return file.previewElement.classList.add("dz-success");
    }
  },

And when the dropzone is initialize..

init: function() {

    this.on("removedfile", function(file) {
      var name = file.previewElement.id;
        $.ajax({
        url: "post URL",
        type: "POST",
        data: { 'name': name}
        });


    });

    return noop;
  },

Now you will receive new image file and you can delete it from server

2

You can add id number of uploaded file on the mockFile and use that id to delete from server.

  Dropzone.options.frmFilesDropzone = {
  init: function() {
    var _this = this;  

    this.on("removedfile", function(file) {
        console.log(file.id); // use file.id to delete file on the server
    });        
    $.ajax({
        type: "GET",
        url: "/server/images",
        success: function(response) {
            if(response.status=="ok"){
                $.each(response.data, function(key,value) {
                    var mockFile = {id:value.id,name: value.name, size: value.filesize};
                    _this.options.addedfile.call(_this, mockFile);
                    _this.options.thumbnail.call(_this, mockFile, "/media/images/"+value.name);
                    _this.options.complete.call(_this, mockFile);
                    _this.options.success.call(_this, mockFile);
                });
            }           
        }
    });

Server Json return for getting all images already uploaded /server/images:

{
"data":[
    {"id":52,"name":"image_1.jpg","filesize":1234},
    {"id":53,"name":"image_2.jpg","filesize":1234},
]}
Dards
  • 91
  • 1
  • 5
0

In my case server sends back some ajax response with deleteUrl for every specific image. I just insert this url as 'data-dz-remove' attribute, set in previewTemplate already.

As I use jquery it looks so:

this.on("success", function (file, response) {
    $(file.previewTemplate).find('a.dz-remove').attr('data-dz-remove', response.deleteUrl);
});

Later this attr used to send ajax post with this url to delete file on server by removedfile event as mentioned above.

igolkotek
  • 1,687
  • 18
  • 16
0

This simple solution will work for single files upload, no need for DOM manipulation.

PHP Upload Script

  [...]
  echo $filepath; // ie: 'medias/articles/m/y/a/my_article/my-image.png'

JS Dropzones

  this.on("success", function(file, response) {
        file.path = response; // We create a new 'path' index
  });
  this.on("removedfile", function(file) {
        removeFile(file.path)
  });

JS outside of Dropzone

var removeFile = function(path){
   //SEND PATH IN AJAX TO PHP DELETE SCRIPT
    $.ajax({
        url: "uploads/delete.php",
        type: "POST",
        data: { 'path': path}
    });
}
Tom Tom
  • 3,680
  • 5
  • 35
  • 40