一。在网上找了很久发现案例都是早些年的版本,现在版本都是用PHP7,导致不能使用。后来找到一篇新版本示例
https://blog.youkuaiyun.com/qq_25600055/article/details/84875145
还有模拟curl请求,不要本地请求本地(我是win下,因为本地win环境只运行了一份PHP-fpm进程)
以下功能代码
// A上传端代码
/**
* curl 上传文件
* @param $file --上传文件(全路径)
* @param $url --请求地址
* @param $aid --用户aid(附加参数)
* @return mixed|string
*/
function upload_file($file, $url, $aid)
{
$data = [
// 还有一种打成数据流的方法.
'pic'=>new \CURLFile($file),
'name' => 'qb',
// 自定义盐签
'token' => 'e10adc3949ba59abbe56e057f20f883e',
'aid' => $aid
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //该curl_setopt可以向header写键值对
curl_setopt($ch, CURLOPT_HEADER, false); // 不返回头信息
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
if ($output == false){
return 'error:' . curl_error($ch);
}
curl_close($ch);
return $output;
}
----------------------------------------------------------------------------------------------------------------------------------->
// B接收端代码
/**
* 获取file数据
* @return array
*/
public function get_file()
{
// file 文件
$file = $_FILES;
// 其他参数
$post = $_POST;
// 接口盐签
$tokne = 'e10adc3949ba59abbe56e057f20f883e';
if (empty($file) || empty($post)){
$res = ['code' => 199 , 'msg' => '文件丢失!'];
return json($res);
}
if ($post['token'] != $tokne){
$res = ['code' => 199 , 'msg' => '鉴权失败!'];
return json($res);
}
if ($file){
$file_data = $this->file_move($file, $post['aid']);
if (!empty($file_data)){
$res = ['code' => 200 , 'msg' => '头像上传成功!'];
return json($res);
}else{
$res = ['code' => 199 , 'msg' => '头像存储失败!'];
return json($res);
}
}
}
/**
* 接口获取file类型文件直接转存
* @param $file
* @param $aid -- 用户aid
* @return array|string
*/
public function file_move($file, $aid)
{
$data = [];
foreach ($file as $image) {
$name = $image['name'];
$type = strtolower(substr($name, strrpos($name, '.') + 1));
$allow_type = ['jpg', 'jpeg', 'gif', 'png'];
//判断文件类型是否被允许上传
if (!in_array($type, $allow_type)) {
continue;
}
// 文件名
// $file_name = date('Ymd') . time() . rand(100, 999) . '.' . $type;
// app_id 命名
$file_name = $aid . '.' . $type;
//开始移动文件到相应的文件夹
if (move_uploaded_file($image['tmp_name'], ROOT_PATH . 'public' . DS . 'data'. DS . 'image' . DS . $file_name)) {
$data = ROOT_PATH . 'public' . DS . 'data'. DS . 'image' . DS . $file_name;
}
}
return $data;
}