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

Laravel中同逻辑文件上传代码在不同控制器失效问题排查

文件上传故障排查:同逻辑代码为何一个正常一个失败?

一、正常工作的PC表单代码

控制器(demandePCController.php)

if($request->hasFile('situation')){
    $image=$request->file('situation');
    $count = count(Storage::files('situation'));
    $prefix='PC-';
    $image_name=$prefix.($count+1).'.'.$image->extension();
    Storage::put("situation/{$image_name}",file_get_contents($request->file('situation')->getRealPath()));
}

视图(demandePC.blade.php)

<div>
    <x-label for="situation" :value="__('Situation Juridique')" />
    <x-input id="situation" class="block mt-1 w-full" type="file" name="situation"/>
</div>

二、无法工作的AL表单代码

控制器(demandeALController.php)

if($request->hasFile('cin')){
    $image=$request->file('cin');
    $count=count(Storage::files('cin'));
    $prefix="AL-";
    $image_name=$prefix.($count+1).".".$image->extension();
    Storage::put("cin/{$image_name}",file_get_contents($request->file('cin')->getRealPath()));
}

视图(demandeAL.blade.php)

<div>    
    <x-label for="cin" :value="__('CIN demandeur')"/>
    <x-input id="cin" class="inline mt-1 w-full" type="file" name="cin"/>
</div>

三、可能的故障原因及排查方向

  • 存储目录问题:检查storage/app/cin目录是否存在,权限是否与situation目录一致。Laravel的Storage::put不会自动创建目录,如果cin目录未手动创建,会直接上传失败。
  • 表单属性缺失:确认AL对应的表单是否添加了enctype="multipart/form-data"属性——这是文件上传的必要条件,PC表单可能已添加但AL表单遗漏。
  • 请求参数拦截:排查是否有中间件对AL表单的请求进行了参数过滤,导致cin文件参数未被正确传递到控制器。
  • 文件限制规则:检查PHP配置(upload_max_filesize、post_max_size)或Laravel验证规则中,是否对cin文件的大小、类型做了更严格的限制,导致文件被拦截。
  • 计数逻辑的隐性问题:Storage::files('cin')仅统计当前目录下的文件,若cin目录之前有文件被手动删除或存在子目录,计数可能异常,但一般不会导致完全无法上传,可临时替换为时间戳命名(如$prefix.time().'.'.$image->extension())测试是否能上传。

内容的提问来源于stack exchange,提问作者Loïc An

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:55:23