Dropzone.js- How to delete files from server?
Asked Answered
C

10

12

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

Circumfluent answered 3/7, 2013 at 15:55 Comment(2)
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 onDuppy
Please refer to my response from the duplicate question.Kugler
T
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]));
}
Tetany answered 3/7, 2013 at 20:18 Comment(2)
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...Tolu
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.Tetany
W
25

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.

Watt answered 21/4, 2014 at 9:46 Comment(3)
Better solution ever! on success response i have a JSON response with fileID. After success event, we underlay that ID!Bathe
NO! Do NOT perform deleting images on the server via removedfile event because when dropzone is destroyed, it calls removeAllFiles in which all images on the server will be destroyed. Related commentPreservative
In new version change var server_file = $(file.previewTemplate).children('.server_file').text(); for var server_file = file.upload.filename;Monsour
T
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]));
}
Tetany answered 3/7, 2013 at 20:18 Comment(2)
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...Tolu
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.Tetany
B
10

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); 
?>
Ballinger answered 10/9, 2014 at 9:3 Comment(0)
C
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 :)

Cordelia answered 21/9, 2016 at 13:17 Comment(0)
W
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) {
            }
        });
    }
Without answered 28/12, 2017 at 19:22 Comment(1)
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).Harder
M
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);
        }
Mcdougald answered 15/10, 2013 at 6:45 Comment(2)
Which URL does the "removedfile" event send request to?Modern
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.Modern
D
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

Doublure answered 14/6, 2017 at 10:48 Comment(0)
B
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},
]}
Benkley answered 28/7, 2019 at 7:0 Comment(0)
J
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.

Jaye answered 6/12, 2014 at 19:13 Comment(0)
B
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}
    });
}
Bucolic answered 15/8, 2016 at 18:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.