You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将zip文件解压到Laravel的SFTP类型Storage存储驱动中?

问题原因

PHP原生ZipArchive类的extractTo()方法仅支持操作本地文件系统,无法适配Laravel Storage的远程磁盘逻辑,你传入的Storage::disk('remote')->path('test_path')会被ZipArchive直接识别为本地路径,因此文件会被解压到本地服务器的对应目录。

解决思路

你需要先把zip文件解压到本地临时目录,再通过Laravel SFTP驱动把解压后的内容批量上传到远程服务器,最后清理本地临时文件即可。

实现代码
$zipPath = $request->zip_file_label;
// 生成本地临时解压目录
$localExtractPath = sys_get_temp_dir() . '/zip_extract_' . uniqid();
if (!is_dir($localExtractPath)) {
    mkdir($localExtractPath, 0755, true);
}

$zip = new ZipArchive;
$res = $zip->open($zipPath);
if ($res === TRUE) {
    // 先解压到本地临时目录
    $zip->extractTo($localExtractPath);
    $zip->close();

    // 遍历解压后的文件上传到远程SFTP
    $files = new \RecursiveIteratorIterator(
        new \RecursiveDirectoryIterator($localExtractPath, \RecursiveDirectoryIterator::SKIP_DOTS),
        \RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($files as $file) {
        $remotePath = 'test_path/' . $files->getSubPathName();
        if ($file->isDir()) {
            // 远程创建目录
            Storage::disk('remote')->makeDirectory($remotePath);
        } else {
            // 上传文件到远程
            Storage::disk('remote')->put($remotePath, file_get_contents($file->getRealPath()));
        }
    }

    // 可选:删除本地临时解压文件
    \File::deleteDirectory($localExtractPath);

    echo "WOOT! $zipPath extracted and uploaded to remote!";
} else {
    echo "Doh! I couldn't open $zipPath";
}
注意事项
  • 确保你的Laravel已经安装了SFTP驱动依赖:league/flysystem-sftp(Laravel 8及以下)或league/flysystem-sftp-v3(Laravel 9及以上)
  • 确认本地服务器可以正常连通SFTP服务器的22端口,且配置的SFTP账号对/var/www/test_path目录有读写权限

内容的提问来源于stack exchange,提问作者Don40

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 14:39:05