|
<?php
/*
Created by Chiwa Kantawong
Created Date 25-03-2009
kchiwa@gmail.com
http://www.zengcode.com
*/
Class UploadObject
{
public $name;
public $saveName;
public $type;
public $files;
public $error;
public $size;
public $status;
private $saveLocation=Null;
public function UploadObject($uploadFile)
{
$this->name = $uploadFile['name'] ;
$this->type = $uploadFile['type'] ;
$this->files = $uploadFile['tmp_name'] ;
$this->error = $uploadFile['error'] ;
$this->size = $uploadFile['size'] ;
$this->saveName = $this->name;
}
public function SaveFile($flag=Null)
/*
$flag = Null => save with old name
$flag = 1 => save with new name md5 with microtime+old name;
$flag = 2 => save with old name+version (not allow replace old version)
*/
{
if ($this->saveLocation == Null)
{
$this->status .= "saveLocation is not define<br> ";
return false;
}else if( !file_exists($this->saveLocation) )
{
$this->status .= $this->saveLocation." not exixts.<br> ";
return false;
}
//generate new file name
if ($flag == 1) $this->saveName = md5(microtime())."_".$this->saveName;
elseif ($flag == 2) $this->saveName = $this->GenerateVesionName();
if (move_uploaded_file ($this->files,$this->saveLocation.$this->saveName ) )
{
$this->status .= "File had save to ==> ".$this->saveLocation.$this->saveName ;
return true;
}
}
public function GenerateVesionName()
{
if (file_exists($this->saveLocation.$this->name) ){
list($name,$ext) = split('\.',$this->name);
$i = 1;
while(true) //loop for new version
{
$newName = $name."_".$i++.".".$ext;
if (!file_exists($this->saveLocation.$newName) ) return $newName;
}
}else{
return $this->name;
}
}
public function SetLocation($location)
{
$this->saveLocation = $location;
}
public function Information()
{
echo "<BR>File Name => ".$this->name;
echo "<BR>File Type => ".$this->type;
echo "<BR>File file => ".$this->files;
echo "<BR>File error => ".$this->error;
echo "<BR>File size => ".$this->size;
echo "<BR>File status => ".$this->status;
echo "<BR>saveLocation => ".$this->saveLocation;
}
}//end class
การเรียกใช้งานตาม code ด้านล่างนี้เลยครับ
if ($_FILES){
$upload = new UploadObject($_FILES['userfile']);
$upload->SetLocation("d:\\www\\course\\files\\");
if ($upload->SaveFile(2) )
{
echo "<BR>Upload successful ".$upload->status;
$upload ->Information();
}else
{
echo "<BR>Upload fail ".$upload->error;
echo "<BR>Upload fail ".$upload->status;
}
}
?>
อันนี้เป็น Form ส่งข้อมูลธรรมดาๆ
<hr>
<U><B>Upload File To Server</B></U>
<hr>
<form action="" method="post" enctype="multipart/form-data">
Browse your files: <input name="userfile" type="file" /><br />
<input type="submit" value="Send files" />
</form>
|