此代码将文件上载到某个目录。现在我想添加文件名检查器以避免覆盖
我创建了一个函数,如果文件名有重复,则返回randomString_filename
,如果不存在重复,则返回确切的文件名。这是用PHP编写的函数:
function rnmFile($dir,$flname){
foreach (glob("$dir*.*") as $filename) {
if ($filename == $flname){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < 10; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString.'_'.$flname;
}
else {
return $flname;
}
}
}
这是文件上传代码:
session_start();
$table_name = $_SESSION['un'];
if (!is_dir($table_name)) {
mkdir($table_name);
}
$output_dir = $table_name . '/';
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
{
if(!is_array($_FILES["myfile"]['name'])) //single file
{
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
echo "<br> Error: ".$_FILES["myfile"]["error"];
$ret[$fileName]= $output_dir.$fileName;
}
else
{
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
$ret[$fileName]= $output_dir.$fileName;
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName );
}
}
}
echo json_encode($ret);
每当我添加该功能时,文件上传似乎都不起作用,我不知道为什么 这就是我将函数添加到代码中的方法:
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.rnmFile($output_dir,$fileName));
$ret[$fileName]= $output_dir.rnmFile($output_dir,$fileName);
并适用于其余部分。 顺便说一下,这是访问文件上传的代码
<div id="content">
<div id="mulitplefileuploader">Upload!</div>
<div id="status"></div>
<script>
$(document).ready(function()
{
var settings = {
url: "upload_logic.php",
method: "POST",
allowedTypes:"jpg,png,gif,doc,pdf,zip",
fileName: "myfile",
multiple: true,
onSuccess:function(files,data,xhr)
{
$("#status").html("<font color='green'>Upload is success</font>");
},
onError: function(files,status,errMsg)
{
$("#status").html("<font color='red'>Upload is Failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
</div>
它还使用jQuery上传插件
答案 0 :(得分:0)
好的,要回答我自己的问题。
变量$fileName
也由jquery.uploadfile.min.js
访问,因此我利用它并将其用作我的变量。我还删除了一些无用的代码,并将glob()
函数替换为file_exsist()
。这是现在正在运行的代码
<?php
session_start();
$table_name = $_SESSION['un'];
if (!is_dir($table_name)) {
mkdir($table_name);
}
$output_dir = $table_name . '/';
if(isset($_FILES["myfile"]))
{
function rnmFile($dir,$flname){
if (file_exists($dir.$flname)){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < 15; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString.'_'.$flname;
}
else {
return $flname;
}
}
}
$fileName = rnmFile($output_dir,$_FILES["myfile"]["name"]);
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.''.$fileName);
?>