我需要帮助。我无法将文件上传到目录。我在下面解释我的代码。
<?php
$dbobj = new DBConnection();
$imageName='newsimage';
$imagePath="../uploads/news/";
$dbobj->uploadImage($_FILES,$imageName,$imagePath,function($image){
print_r($image);exit;
});
class DBConnection{
public function uploadImage($files,$imageFieldName,$imageDirPath,$callback){
// echo $imageField;exit;
// print_r($files[$imageFieldName]);exit;
$result=array();
$imageName=generateRandomNumber().'_'.$_FILES[$imageFieldName]['name'];
$target_dir = $imageDirPath;
$target_file = $target_dir . basename($imageName);
$uploadOk = 1;
//echo $files[$imageFieldName]["tmp_name"] ;exit;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
//echo $imageName;exit;
if (file_exists($target_file)) {
$result['msg']="Sorry, file already exists.";
$result['num']=0;
$callback($result);
$uploadOk = 0;
}
if ($_FILES[$imageFieldName]["size"] > 500000) {
$result['msg']="Sorry, file size is large.";
$result['num']=0;
$callback($result);
$uploadOk = 0;
}
if($imageFileType != "jpg") {
$result['msg']="Sorry, only .jpg,.jpeg and .png files are allowed.";
$result['num']=0;
$callback($result);
$uploadOk = 0;
}
if ($uploadOk == 0) {
$result['msg']="Sorry, Your file could not uploaded.";
$result['num']=0;
$callback($result);
}else{
if (move_uploaded_file($_FILES[$imageFieldName]['tmp_name'], $target_file)) {
$result['msg']="Image has uploaded successfully.";
$result['num']=1;
$callback($result);
}else{
$result['msg']="Sorry, Your Image could not uploaded to the directory.";
$result['num']=0;
$callback($result);
}
}
}
}
function generateRandomNumber(){
$result=base_convert((float)rand()/(float)getrandmax() * round(microtime(true) * 1000), 10, 36);
return $result;
}
?>
在这里,我试图将 $_FILES
设置为参数。在 uploadImage
函数中,我试图回显图像名称,但我没有得到它。所以我不能将文件上传到文件夹中。请帮我解决此问题。
最佳答案
$_POST、$_GET 和 $_FILES 是 super 全局变量,它们始终可用。因此将它们作为函数参数传递是个坏主意。
而不是将 $_FILES 作为函数参数传递,尝试在函数本身中获取它。
class DBConnection{
public function uploadImage($imageFieldName,$imageDirPath,$callback)
{
echo $_FILES[$imageFieldName]['name'];
echo $_FILES[$imageFieldName]['tmp_name'];
}
}
希望对你有帮助。
关于php - 使用PHP和MySQL无法获取文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35310861/