关于PHP,我非常初级,但是,似乎我的图像上传器可以按照以下代码(我在网上获得)的方式工作。唯一的问题是,当用户将文件上传到唯一的文件(例如用户/日期)时,我需要重命名文件。更改此代码后,似乎无法正常工作。
我花了一些时间在这里和整个互联网上进行搜索,但是我一直在努力寻找合适的东西。
请有人为我提供修复或指导我正确的方向。
感谢堆栈溢出
class Uploader {
private $files = array();
private $extensions = array();
private $errors = array();
private $store_directory = "./attachment";
private $resize_image_library_instance = null;
public function __construct($files) {
if (is_array($files) === false) {
$files[] = $files;
}
$this->files = $files;
}
public function set_upload_to($store_directory) {
$this->store_directory = $store_directory;
}
public function set_valid_extensions($extensions, $case_sensitive = false) {
$this->extensions = $extensions;
$this->case_sensitive = $case_sensitive;
}
public function set_resize_image_library($resize_image_library_instance) {
$this->resize_image_library_instance = $resize_image_library_instance;
}
public function is_valid_extension() {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
if (empty($this->files['name'][$i]) === false) {
$file_extension = $this->get_extension($this->files['name'][$i]);
if (in_array($file_extension, $this->extensions) === false) {
$this->errors['type'] = "extension";
$this->errors['file_name'] = $this->files['name'][$i];
$this->errors['file_extension'] = $file_extension;
return false;
}
}
}
return true;
}
public function run() {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
if (empty($this->files['name'][$i]) === false) {
if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$this->files['name'][$i]) == false) {
$this->errors['type'] = "run";
$this->errors['file_name'] = $this->files['name'][$i];
}
}
}
return empty($this->errors);
}
public function resize($scale_size = 200) {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
$image = realpath($this->store_directory.'/'.$this->files['name'][$i]);
if (file_exists($image) === true && is_file($image) === true) {
$this->resize_image_library_instance->init($image);
$this->resize_image_library_instance->scale($scale_size);
if ($this->resize_image_library_instance->save($image) === false) {
$this->errors['type'] = "resize";
$this->errors['file_name'] = $image;
}
}
}
return empty($this->errors);
}
public function get_errors() {
return $this->errors;
}
//
private function get_extension($filename) {
$info = pathinfo($filename);
return $info['extension'];
}
private function get_filename($file) {
$info = pathinfo($file);
return $info['filename'];
}
}
答案 0 :(得分:1)
要为上载的文件生成唯一的名称并将其保存到服务器,可以使用time(),mt_rand(),然后一起使用上载的文件名。这样。
public static function generateUniqueFileName($fileName)
{
return time() . mt_rand(100, 100000) . $fileName;
}
如果您还希望在用户名前添加用户名,则可以将其传递给方法,并在开始时进行连接。