1.接收前端传过来的文件接口
public function index()
{
$upload_path = DS . 'uploads' . DS .'image'.DS.date('Ymd', time()).DS;
$public_path = 'public' . $upload_path;
$type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$new_file_url=ROOT_PATH.$public_path;
$new_file = ROOT_PATH.$public_path.$file_name;
if(!file_exists($new_file_url)){
mkdir($new_file_url,0777,true);
}
/*移动到临时文件*/
move_uploaded_file($tmp_name,$new_file);
$data = [
'file' => new \CURLFile(realpath($new_file)),//'@'.realpath($tmp_name)
'fileName'=>$file_name
];
$data['file']->name= iconv('utf-8', 'gbk', $data['file']->name); //处理中文名文件
$url='http://localhost/public/index.php/index/index/addFaImg'; //要发送到的url地址
$res = $this->post($url,$data); //post提交数据
if($res){
$data = json_decode($res,true);
return json($data);
}
}
function post($url , $data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// POST数据
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$curlErrNo = curl_errno($ch);
$curlErr = curl_error($ch);
curl_close($ch);
return $output;
}
2.另一个服务器接收curl传送的文件
<?php
namespace app\index\controller;
use app\common\facade\Upload;
class index
{
public function addFaImg()
{
// 获取curl传过来的文件
$file = request()->file('file');
$path='uploads/fa_image/';
$res =Upload::upload($file,$path);
return ['code' => 20000 , 'msg' => '上传成功','data' => $res];
}
}
3.自己封装的上传文件的代码-------在application\common\facade里
<?php
namespace app\common\facade;
class Upload
{
public static function upload($file, $path, $data = null)
{
// 获取表单上传文件 例如上传了001.jpg
// 移动到框架应用根目录/uploads/ 目录下
$up_dir = $path.date('Ymd', time()) . "/"; //创建目录
if(!file_exists($up_dir)){
mkdir($up_dir,0777,true);
}
$info = $file->validate(['ext'=>'webp,jpg,png,gif,jpeg,mp4,AVI,MOV'])->rule('md5')->move($up_dir);
if($info){
// 成功上传后 获取上传信息
$res = $info->getSaveName();
// 输出 42a79759f284b767dfcb2a0197904287.jpg
return str_replace("\\",'/',$up_dir.$res); //将反斜杆转为正斜杠 ;
}else{
// 上传失败获取错误信息
$res = $file->getError();
return $res;
}
}
}
|