向上传的文件添加随机数

时间:2012-10-11 18:53:43

标签: php ajaxuploader

我正在使用Valum的Ajax-Uploader脚本将文件上传到我的服务器。因为上传的文件很可能具有相同的名称,所以我在文件名中添加了一个随机数。问题是ajax上传器将原始文件名返回到input[type=text]而不是添加了随机数的新文件名。我尝试过echo $file;而不是echo "success";,但所有发生的事情都是上传文件,脚本会返回弹出错误。

jQuery(function() {
    var url = "http://example.com/uploads/samples/";
    var button = jQuery('#up');
    new AjaxUpload(button, {
        action: 'upload.php',
        name: 'upload',
        autoSubmit: true,
        onSubmit: function(file, ext) {
            // do stuff while file is uploading
        },
        onComplete: function(file, response) {
            if (response === "success") {
                $('input[type=text]').val(url + file);
            } else {
                jAlert('Something went wrong!', 'Error!');
            }
        }
    });
});

upload.php的

<?php
    $uploaddir = '/path/to/uploaddir/'; 
    $file = basename($_FILES['file']['name']);

     if($_FILES['file']['name']) {
      $file = preg_replace('/\s+/', '_', $file);
      $rand = rand(0000,9999);

      if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $rand . $file)) { 
            echo "success";
        } else {
            echo "error";
        }
    }
?>

3 个答案:

答案 0 :(得分:1)

更改

$('input[type=text]').text(url + file);

$('input[type=text]').val(url + file);

答案 1 :(得分:0)

我建议使用日期和时间创建一个唯一的随机数。 您可以在代码中使用以下函数,我完全信任此函数,因为我已在项目中使用它。

`
    /**
    * This function return unique string as a key 
    */
    public static function getUniqueKey(){      
        $currentDateTime = date("YmdHisu");
        return $currentDateTime . BTITTools::createRandomString(3);
    }
`

@ My Code Programs

答案 2 :(得分:0)

客户端代码和服务器代码完全相互独立。基本上,您的JavaScript代码无法知道您的PHP代码刚才做了什么。在PHP文件中更改它时,url不会自动更新。

另一种解决方案是让您的PHP代码回显新文件名,或者回显错误消息。

例如:

<强> PHP

<?php
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $rand . $file)) {   
    // Everything went well! Echo the dollar sign ($) plus the new file name
    echo '$' . $_FILES['file']['tmp_name'], $uploaddir . $rand . $file;   
} else {  
    echo "error";  
}  
?>

<强> JS

onComplete: function(file, response) { 
    // If the first character of the response is the "$" sign
    if (response.substring(0,1) == "$") { 
        $('input[type=text]').val(response.substring(1));
    } else { 
        jAlert('Something went wrong!', 'Error!'); 
    } 
} 
相关问题