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 协议》,转载必须注明作者和本文链接
朝着梦,踏平坎坷
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

第一次上传时拿到的路径时php缓存的tmp文件,用curl传过去识别不了tmp文件怎么办

5年前 评论
逆天西瓜 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!