使用情景
多个项目,一台图片存储服务器,方便做CDN
上传图片
<?php
//上传用户商品图
$path = 'merchant/goods/';
$file = request()->file('up_img');
//创建一个 CURLFile 对象, 用与上传文件。filename上传文件的路径 mimetype文件的Mimetype postname文件名。
$cfile = curl_file_create($file->getInfo('tmp_name'), $file->getInfo('type'), str_replace('/', '_', $path));
$remote_data = [
'file' => $cfile,
'post_data' => 'test'
];
$jsdata_url = 'http://cdn.img.abc.cn/upload.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $jsdata_url);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $remote_data);
$response = curl_exec($curl);
curl_close($curl);
if($response==400){
$this->ajaxReturn("上传失败!");
} else {
return $response;
}
存储图片
$file = $_FILES['file'];//图片文件
if (isset($file['type'])) {
$type_arr = explode('/', $file['type']);
} else {
echo 400;
exit;
}
$name= empty($file['name']) ? 'common/' : str_replace('_', '/', $file['name']);
$dir = $name.date('Y').date('m').'/'.date('d');
if (!file_exists ($dir)) {
mkdir ($dir, 0777, true );
}
$filepath = $dir.'/'.md5(microtime(true)).'.'.$type_arr[1];
$tmp = $file['tmp_name'];
if(move_uploaded_file($tmp,$filepath)){
echo 'http://cdn.img.abc.cn/'.$filepath; //成功
} else {
echo 400;//失败
}