jQuery Dropzone.js - 如何在上传到文件夹之前更改文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24859005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:40:44  来源:igfitidea点击:

Dropzone.js - How to change file name before uploading to folder

jqueryimage-uploadingdropzone.js

提问by Mr.Happy

I am using DropzoneJSscript 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.

我正在使用DropzoneJS脚本通过拖放上传图像,但现在我正在寻找一种解决方案,用于在上传到服务器文件夹之前如何添加带有文件名的当前时间戳,因为如果文件夹中已存在文件。

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

我也在下面的 stackoverflow 链接中提到过,但我很困惑在哪里实现这个。

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

Here is dropzone.js scriptfor reference

这是dropzone.js 脚本以供参考

回答by Rajnikanth

Please check following code I have implemented using PHP.

请检查我使用 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

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

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 :)

希望这对使用ajax上传图片和使用ajax删除有帮助:)

I have found from following references:

我从以下参考资料中找到:

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

Dropzone.js- 如何从服务器删除文件?Dropzone.js 用 php 删除按钮

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

还要在 dropzone.js 文件中的第 #1110 行之后添加以下代码,以防止用户上传同名的重复文件:)

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

参考链接: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

回答by Kalaschni

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

要在每次上传前为文件名添加时间戳,您有两种选择,具体取决于您的 DropzoneJS 版本。

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

DropzoneJS 5.1+的较新版本确实有一个renameFile函数,使用如下:

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


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

旧版本v4.3 - v5.1 中,这有点不同。

In this versions there is a renameFilenameoption, this is used like this:

在这个版本中有一个renameFilename选项,它是这样使用的:

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

Happy coding, Kalasch

快乐编码,Kalasch

回答by sixstring

I just used the standard php file rename.

我只是使用了标准的 php 文件重命名。

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

这对我来说效果很好,而且实施起来非常简单。.jpg 扩展名可能不推荐用于硬编码,但在我的场景中,我只获取 jpg 文件类型。