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

Laravel中AJAX文件上传返回null,验证提示文件必填的问题

问题原因及解决方案

你的问题出在AJAX请求的data参数传递方式上:

  • 你当前写的data: {fd}是把FormData对象包裹在一个新的字面量对象里发送,这会导致后端接收时,file字段被嵌套在fd这个键下面,所以Laravel的$request无法直接获取到file,验证自然提示必填。

修正后的AJAX代码

var files = $('#imgur_attach')[0].files;

if(files.length > 0){
  var fd = new FormData();
  
  // Append data 
  fd.append('file',files[0]);
  fd.append('_token',$globalToken);

  $.ajax({
      type: "POST",
      dataType: "json",
      contentType: false,
      processData: false,
      url: host + "/attach-comment-image/" ,
      data: fd, // 直接传入FormData对象,不要用{}包裹
      success: function(response) {
          console.log(response);
      },
      error: function(xhr) {
          console.log(xhr.responseText);
      }
  });
}

控制器补充说明

验证通过后,你可以通过以下方式获取上传的文件:

public function attach(Request $request) {
    
    $this->validate($request, [
        'file' => 'image|required',
    ]);     
    
    // 获取上传的文件实例
    $file = $request->file('file');
    // 后续可执行存储等操作,例如:
    // $storagePath = $file->store('comment_images');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:40:26