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

Laravel 9文件上传路径错误:误创建public文件夹而非指向public_html

Laravel文件上传路径异常问题解决

问题描述

项目本地public目录下设有文件上传文件夹,服务器部署时项目主体在public_html目录外,仅index文件放在public_html中。已尝试修改路径指向public_html,但上传文件时Laravel并未将文件存入public_html,反而自动创建了一个public文件夹并把文件传到里面。输出public_path()发现它指向项目内的原始public文件夹,而非public_html。

相关代码:

function saveImageWithName($name,$photo,$folder)
{
    $file_extension = $photo->getClientOriginalExtension();
    $file_name = $name . '.' . $file_extension;
    $path = $folder;
    $this->removeImage($path . $file_name);
    $photo->move($path,$file_name);
    return $file_name;
}

function removeImage($path)
{
    if (!File::exists($path))
        return true;
    return File::delete($path);
}

注:了解Laravel的storage机制,但需求是将文件直接上传至public_html目录。本地和生产环境均出现该问题,修改文件夹权限为777无效,相同PHP及Laravel版本的其他项目无此异常。

解决方案

  • 重新定义public_path()指向
    打开public_html目录下的index.php文件,在引入bootstrap/app.php的代码前,添加路径定义:

    // 定义public_html为公共目录
    define('PUBLIC_PATH', __DIR__);
    $app = require_once __DIR__.'/../bootstrap/app.php';
    // 绑定正确的公共路径到Laravel容器
    $app->bind('path.public', function () {
        return __DIR__;
    });
    

    这样Laravel的public_path()就会指向public_html目录。

  • 修正上传路径参数
    调用saveImageWithName函数时,传入的$folder参数要基于正确的公共路径,比如使用public_path('uploads')(假设上传文件夹是uploads),确保路径指向public_html下的目标文件夹,避免使用相对路径导致的错误。

  • 检查文件系统配置
    打开config/filesystems.php,确认public磁盘的root配置指向正确的路径:

    'public' => [
        'driver' => 'local',
        'root' => public_path(),
        'visibility' => 'public',
    ],
    

    这里的root会自动使用我们重新定义的public_path(),确保和public_html一致。

  • 清除配置缓存
    执行以下命令清除Laravel的配置缓存,让新的路径设置生效:

    php artisan config:clear
    php artisan cache:clear
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 15:18:26