CURL 发送文件
代码备份录——CURL 发送文件文件
说明:表单提交文件 -> laravel接收 -> curl提交给另一个服务端
html 部分
<form action="/testFile" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
配置路由
// form 提交
Route::any("/testFile","TestController@testFile");
// form action 接收
Route::any("/testLoadFile","TestController@testLoadFile");
服务端组装CURLfile,并发送另一个服务端
public function testFile(Request $request){
$data = array(
'file'=> new \CURLFile(realpath($request->file('file')->path())),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"/testLoadFile");//此处以当前服务器为接收地址
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);//设置最长等待时间
curl_setopt($ch, CURLOPT_POST, 1);//post提交
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$data = curl_exec($ch);//执行
if(curl_errno($ch)){
return curl_error($ch);
}
curl_close($ch);//释放
return json_encode($data);
}
模拟另一个服务端作为接收
public function testLoadFile(Request $request){
if ($request->hasFile('file')) {
if ($request->file('file')->isValid()){
// 上传成功
// 随机名字 . 后缀
$fileName = "other/".Date("YmdHis").substr(md5(time()),5,15).".".$request->file("file")->extension();// 需要 开启php_fileinfo 扩展 否则会报错
// 获取临时上传的路径(如果不存在本地,则方法调用完之后,会被删除)
//$fileUrl = $request->file('file')->path();
// 可选存储在本地
$fileUrl = $request->file("file")->move(__DIR__."/",$fileName);
return ($fileUrl);
}
}
return json_encode([]);
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
第一次上传时拿到的路径时php缓存的tmp文件,用curl传过去识别不了tmp文件怎么办
使用guzzle更方便点,参考 博客:Lumen 使用 Guzzle 替代 curl