18

I am using DropzoneJS script for uploading images with drag & drop, but now I'm looking for a solution for how to add current timestamps with file name before uploading to the server folder, because I am not able to upload the same image if the file already exists in the folder.

I have also referred below stackoverflow link but I'm confused where to implement this.

  1. https://stackoverflow.com/a/23805488/3113858
  2. https://stackoverflow.com/a/19432731/3113858

Here is dropzone.js script for reference

Community
  • 1
  • 1
Mr.Happy
  • 2,639
  • 9
  • 40
  • 73
  • Hello, Did you find any solution for this issue. if yes then could you please share it. if possible with an example code. thank you – JSB Nov 02 '14 at 08:32
  • @JasbirBhinder Not found any solution. – Mr.Happy Nov 03 '14 at 04:25
  • Ok. And are you using dropzone with asp.net. I am trying to call webmethod from dropzone url but it is not working. Dropzone Returning html response back page. – JSB Nov 04 '14 at 18:34
  • I have used dropzone with PHP. – Mr.Happy Nov 05 '14 at 04:14
  • 1
    you can change the name on server-side and return it after success on upload, and use jquery trick to replace the old name with new returned name – Somwang Souksavatd Nov 17 '14 at 08:15
  • Please change the accepted answer to my one, it is much simpler and keeps the rename on the client side. :-) – Kalaschni Mar 27 '17 at 07:16

3 Answers3

24

Please check following code I have implemented using PHP.

Use Following code in your index file

$(document).ready(function() {
            Dropzone.autoDiscover = false;
            var fileList = new Array;
            var i =0;
            $("#some-dropzone").dropzone({
                addRemoveLinks: true,
                init: function() {

                    // Hack: Add the dropzone class to the element
                    $(this.element).addClass("dropzone");

                    this.on("success", function(file, serverFileName) {
                        fileList[i] = {"serverFileName" : serverFileName, "fileName" : file.name,"fileId" : i };
                        //console.log(fileList);
                        i++;

                    });
                    this.on("removedfile", function(file) {
                        var rmvFile = "";
                        for(f=0;f<fileList.length;f++){

                            if(fileList[f].fileName == file.name)
                            {
                                rmvFile = fileList[f].serverFileName;

                            }

                        }

                        if (rmvFile){
                            $.ajax({
                                url: "http://localhost/dropzone/sample/delete_temp_files.php",
                                type: "POST",
                                data: { "fileList" : rmvFile }
                            });
                        }
                    });

                },
                url: "http://localhost/dropzone/sample/upload.php"
            });

        });

Upload.php

<?php
$ds = DIRECTORY_SEPARATOR;  // Store directory separator (DIRECTORY_SEPARATOR) to a simple variable. This is just a personal preference as we hate to type long variable name.
$storeFolder = 'uploads';   // Declare a variable for destination folder.
if (!empty($_FILES)) {

    $tempFile = $_FILES['file']['tmp_name'];          // If file is sent to the page, store the file object to a temporary variable.
    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;  // Create the absolute path of the destination folder.
    // Adding timestamp with image's name so that files with same name can be uploaded easily.
    $date = new DateTime();
    $newFileName = $date->getTimestamp().$_FILES['file']['name'];
    $targetFile =  $targetPath.$newFileName;  // Create the absolute path of the uploaded file destination.
    move_uploaded_file($tempFile,$targetFile); // Move uploaded file to destination.

    echo $newFileName;
}
?>

delete_temp_files.php

<?php
$ds = DIRECTORY_SEPARATOR;  // Store directory separator (DIRECTORY_SEPARATOR) to a simple variable. This is just a personal preference as we hate to type long variable name.
$storeFolder = 'uploads'; 

$fileList = $_POST['fileList'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;


if(isset($fileList)){
    unlink($targetPath.$fileList);
}

?>

Hope this will be helpful for uploading images using ajax and delete using ajax :)

I have found from following references:

Dropzone.js- How to delete files from server? Dropzone.js remove button with php

Also add following code in your dropzone.js file after line #1110 for preventing user to upload duplicate files with same name :)

Dropzone.prototype.addFile = function(file) {
    if (this.files.length) {
        var _i, _len;
        for (_i = 0, _len = this.files.length; _i < _len; _i++) {
            if(this.files[_i].name === file.name && this.files[_i].size === file.size) {
                return false;
        }
    }
}

Reference Link: https://www.bountysource.com/issues/2993843-dropzone-did-not-check-the-duplicate-file-on-addfile?utm_campaign=plugin&utm_content=tracker%2F283989&utm_medium=issues&utm_source=github

Dan
  • 919
  • 1
  • 10
  • 28
Rajnikanth
  • 2,745
  • 6
  • 31
  • 46
  • 1
    @Mr.Happy Where is it adding timestamp? My requirement is to rename file before upload and also show new renamed file name in preview. – Volatil3 Jan 04 '16 at 10:08
23

To prefix the filename with a timestamp each time before upload, you have two options depending on you version of DropzoneJS.

The newer versions of DropzoneJS 5.1+ does have a renameFile function that is used as followed:

    ...
    renameFile: function (file) {
        return new Date().getTime() + '_' + file.name;
    }
    ...

In older versions v4.3 - v5.1 this is done a little bit different.

In this versions there is a renameFilename option, this is used like this:

Dropzone.autoDiscover = false;
$(document).ready(function () {
    $(".dropzone").dropzone({
        renameFilename: function (filename) {
            return new Date().getTime() + '_' + filename;
        }
    });
});

Happy coding, Kalasch

Kalaschni
  • 2,301
  • 24
  • 37
  • Note that this also appears to rename the filename on init for preloaded images from your server as well. @Kalaschni - do you know if there's a way to only implement a file rename on upload? – wazdev Jul 09 '16 at 13:00
  • 1
    @wazdev you could examine the filename passed to the callback... if it already appears to be renamed, return it untouched. :| – Brad Kent Oct 20 '16 at 18:59
  • this should be the accepted answer! it is so much simpler and gets the job done on the client side. – Parik Tiwari Mar 24 '17 at 01:15
  • @ParikTiwari I too have done the same. But file.name is not getting modified to new name. Here is my code. Can someone spot any problems? Dropzone.autoDiscover = false; document.addEventListener("DOMContentLoaded", function() { var UPLOAD_URL = decodeURIComponent('<%=storageUrl%>'); var myDropzone = new Dropzone("#upload-widget", { url: UPLOAD_URL, paramName: 'files[]', addRemoveLinks: true, acceptedFiles: 'application/pdf', renameFile: function (file) { file.name = 'some-random-name'; } }); – prem911 Apr 04 '18 at 13:30
  • @prem911: which version of Dropzone do you use? – Kalaschni Apr 09 '18 at 14:27
  • 1
    @Kalaschni I m using the latest version 5.4. The surprising thing is that the deprecated API renameFilename worked. However, renameFile is still not working. This is going against the spirit of the documentation. I will raise a defect in github page – prem911 Apr 10 '18 at 02:51
  • 3
    For anyone struggling with version 5.1+ the code here is incorrect. It's needs to be: `renameFile: function (file) { return new Date().getTime() + '_' + file.name; }` – Max Nov 20 '19 at 15:04
  • Thanks for pointing that out @Max, I have changed my answer accordingly. :) – Kalaschni Nov 21 '19 at 14:54
0

I just used the standard php file rename.

$targetFile =  $targetPath . $_FILES['file']['name']; //the original upload
$newfilename = "somename" . $variable . ".jpg"; //a new filename string

rename($targetFile , $new); //rename at the end of the function

This worked well for me and was pretty simple to implement. The .jpg extension is probably not recommended to hard code but in my scenario im only getting jpg file types.

sixstring
  • 262
  • 4
  • 10