/**
*注意,一共有三個地址,假設圖片存儲地址爲“../../AAA/BBB/CCC.jpg”,1、後端定死“../../AAA”,2、前端傳過來“/BBB”,後端生成“/CCC.jpg”
*本接口,圖片信息使用post傳值,但path參數無法攜帶,故使用get傳path;若您有其他好辦法,還望留言相告
*/
//1、封裝接口類
class uploadImageAjax{
private $uptypes =[//上傳文件類型列表
'image/jpg',
'image/jpeg',
'image/png',
'image/pjpeg',
'image/gif',
'image/bmp',
'image/x-png'
];
private $base_name = "/weixinpl/up";
public $max_upload_size = 2;//2M
private $save_path = "../../../up";//圖片存儲路徑,基準根路徑
private $path = "";//上傳文件存儲的文件地址
private $name = "";//本地文件名稱
private $type = "";//文件類型
private $tmp_name = "";//上傳後臨時文件名稱
private $error = "";//錯誤信息
private $size = "";//文件大小
private $new_file_name = "";//新文件名稱
function __construct($file,$path)
{
$this->path = $path;
$this->save_path = $this->save_path.$path;//拼接保存地址
if(!file_exists($this->save_path)){//文件夾不存在,創建文件夾
mkdir($this->save_path);
}
$this->name = $file['name'];
$this->type = $file['type'];
$this->tmp_name = $file['tmp_name'];
$this->error = $file['error'];
$this->size = $file['size'];
$this->new_file_name = "/".time().".".pathinfo($file["name"])['extension'];
}
/**
* 檢測文件是否通過HTTP上傳
* @return bool
*/
public function check_source(){
if(!is_uploaded_file($this->tmp_name)){
return false;
}
return true;
}
/**
* 檢測文件類型是否允許上傳
* @return bool
*/
public function check_type(){
if(!in_array($this->type, $this->uptypes)){
return false;
}
return true;
}
/**
* 驗證文件大小
* @return bool
*/
public function check_size(){
if($this->size > $this->max_upload_size*1024*1024){
return false;
}
return true;
}
/**
* 移動臨時文件到指定文件夾
* @return bool|string
*/
public function upload_image(){
if(!move_uploaded_file($this->tmp_name, $this->save_path.$this->new_file_name)){
return false;
}
return $this->base_name.$this->path.$this->new_file_name;//返回完整路徑
}
function __destruct()
{
// TODO: Implement __destruct() method.
}
}
//2、實例化調用
$model = new uploadImageAjax($_FILES['file'],$_GET['path']);
if(!$model->check_source()){
echo json_encode([
'code' => -1,
'msg' => '文件不存在',
]);die;
}
if(!$model->check_type()){
echo json_encode([
'code' => -2,
'msg' => '不允許上傳此類型文件',
]);die;
}
if(!$model->check_size()){
echo json_encode([
'code' => -3,
'msg' => "文件不允許超過{$model->max_upload_size}M",
]);die;
}
$result = $model->upload_image();
if($result){
echo json_encode([
'code' => 1,
'msg' => '上傳成功',
'path' => $result
]);die;
}else{
echo json_encode([
'code' => -4,
'msg' => '上傳失敗',
]);die;
}
Ajax-php 圖片上傳(已整理)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.