如何使用Laravel实现文件上传至OneDrive?
Laravel 上传文件至 OneDrive 实用方案
方案一:使用 Microsoft Graph SDK(官方推荐)
这是最稳定的官方方案,步骤清晰:
- 先在Azure Active Directory中注册应用,获取
客户端ID、客户端密钥、租户ID,并配置重定向URI(用于OAuth授权) - 安装SDK:
composer require microsoft/microsoft-graph - 在
.env中添加配置:AZURE_CLIENT_ID=你的客户端ID AZURE_CLIENT_SECRET=你的客户端密钥 AZURE_TENANT_ID=你的租户ID - 编写上传逻辑(示例控制器方法):
注:若需上传到指定文件夹,可修改API路径为use Microsoft\Graph\Graph; public function uploadToOneDrive(Request $request) { $file = $request->file('upload_file'); if (!$file) { return back()->with('error', '请选择文件'); } // 获取访问令牌(实际项目建议封装为服务类) $graph = new Graph(); $token = $graph->getAccessTokenForApp( env('AZURE_TENANT_ID'), env('AZURE_CLIENT_ID'), env('AZURE_CLIENT_SECRET'), ['https://graph.microsoft.com/.default'] ); $graph->setAccessToken($token); // 上传文件到OneDrive根目录 $graph->createRequest("PUT", "/me/drive/root:/{$file->getClientOriginalName()}:/content") ->attachBody($file->getContent()) ->execute(); return back()->with('success', '文件上传成功'); }/me/drive/items/{文件夹ID}/children/{文件名}/content
方案二:自定义 Laravel Filesystem 驱动(贴合Laravel生态)
用Laravel熟悉的Storage门面操作,学习成本更低:
- 安装适配器包:
composer require league/flysystem-onedrive "^3.0" - 在
config/filesystems.php的disks数组中添加onedrive配置:'onedrive' => [ 'driver' => 'onedrive', 'client_id' => env('AZURE_CLIENT_ID'), 'client_secret' => env('AZURE_CLIENT_SECRET'), 'tenant_id' => env('AZURE_TENANT_ID'), 'redirect_uri' => env('AZURE_REDIRECT_URI'), // 需和Azure配置一致 'scope' => 'Files.ReadWrite.All', ], - 上传文件只需一行代码,和本地存储逻辑一致:
public function upload(Request $request) { $file = $request->file('upload_file'); if ($file) { $path = Storage::disk('onedrive')->put('uploads', $file); return "文件已上传至OneDrive,路径:{$path}"; } return '请选择文件'; }
方案三:直接调用 Microsoft Graph API(理解底层逻辑)
适合想手动处理请求的新手,无需依赖SDK:
- 先通过OAuth2流程获取访问令牌(步骤:引导用户授权获取授权码,再用授权码换取access_token)
- 用Laravel Http客户端发送上传请求:
use Illuminate\Support\Facades\Http; public function uploadViaApi(Request $request) { $file = $request->file('upload_file'); $accessToken = '你的访问令牌'; // 实际需从授权流程获取 $response = Http::withHeaders([ 'Authorization' => "Bearer {$accessToken}", 'Content-Type' => $file->getMimeType(), ])->put( "https://graph.microsoft.com/v1.0/me/drive/root:/{$file->getClientOriginalName()}:/content", file_get_contents($file->getPathname()) ); return $response->successful() ? '上传成功' : '上传失败:' . $response->body(); }
内容的提问来源于stack exchange,提问作者Huu_Tu
相关产品推荐
相关产品推荐

