我无法使用ajax传递img?

发布于 2025-01-17 01:44:25 字数 3997 浏览 0 评论 0原文

我试图在添加新航空公司时包含徽标,但我不知道如何使用 ajax 将文件类型的输入传递到控制器。我尝试使用 FormData()。我没有收到任何错误,但文件没有传递到控制器我查看了一些与我的问题类似的问题,但我找不到解决方案。

<form action="javascript:void(0)" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
              <input type="hidden" name="id" id="id">
              <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Name</label>
                <div class="col-sm-12">
                  <input type="text" class="form-control" id="name" name="name" placeholder="Enter Airline Name" value="" maxlength="50" required="">
                </div>
              </div>  
              <div class="form-group">
                <label for="name" class="col-sm-2 control-label">country</label>
                <div class="col-sm-12">
                  <input type="text" class="form-control" id="country" name="country" placeholder="Enter Airline country" value="" maxlength="50" required="">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">Logo</label>
                <div class="col-sm-12">
                  <input type="file" class="form-control" id="logo" name="logo" placeholder="Enter Airline Code" value="" required="">
                </div>
              </div>
              <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary" id="btn-save" value="addNewBook">Save changes
                </button>
              </div>
            </form>

ajax:

  $('body').on('click', '#btn-save', function (event) {
      event.preventDefault()
          var id = $("#id").val();
          var name = $("#name").val();
          var country = $("#country").val();
          let logo = new FormData(document.getElementById("addEditBookForm"));
          $("#btn-save").html('Please Wait...');
          $("#btn-save"). attr("disabled", true);
         
        // ajax
       
        $.ajax({
            type:"POST",
            url: "{{ url('admin/add-update-Airlines') }}",
            data: {
              id:id,
              name:name,
              country:country,
              logo:logo,
            },
            contentType: false,
            processData:false,
            cache: false,
            dataType: 'json',
            success: function(res){
             window.location.reload();
            $("#btn-save").html('Submit');
            $("#btn-save"). attr("disabled", false);
            Swal.fire(
            'Good job!',
            'You clicked the button!',
            'success'
            )
           }
        
        });
      
    });

控制器:

 public function store(Request $request)
    {
        

        $newImgName = time() . '-' . $request->name . '.' .$request->logo->extension();
        $request->logo->move(public_path('img'),$newImgName);
        $Airline   =   Airline::updateOrCreate(
                    [
                        'id' => $request->id
                    ],
                    $request->validate([
                        'name' => ['required', 'string', 'max:255'],
                        'country' => ['required', 'string', 'max:255'],
                        'logo' => ['required|mimes:ipg,png,jpeg|max:5048'],            
                    ]),
                   
                    [
                        'name' => $request->name, 
                        'country' => $request->country,
                        'logo' => $newImgName,
                    ]);
    
                 return response()->json(['success' => true]);
    }

I'm trying to include a logo when adding a new airline, but I don't know how can I pass input with file type to the controller with ajax. I tried to use FormData(). I did not get any error, but the file was not passed to the controller I have looked at some questions similar to my problem, but I can't find a solution.

<form action="javascript:void(0)" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
              <input type="hidden" name="id" id="id">
              <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Name</label>
                <div class="col-sm-12">
                  <input type="text" class="form-control" id="name" name="name" placeholder="Enter Airline Name" value="" maxlength="50" required="">
                </div>
              </div>  
              <div class="form-group">
                <label for="name" class="col-sm-2 control-label">country</label>
                <div class="col-sm-12">
                  <input type="text" class="form-control" id="country" name="country" placeholder="Enter Airline country" value="" maxlength="50" required="">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">Logo</label>
                <div class="col-sm-12">
                  <input type="file" class="form-control" id="logo" name="logo" placeholder="Enter Airline Code" value="" required="">
                </div>
              </div>
              <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary" id="btn-save" value="addNewBook">Save changes
                </button>
              </div>
            </form>

ajax:

  $('body').on('click', '#btn-save', function (event) {
      event.preventDefault()
          var id = $("#id").val();
          var name = $("#name").val();
          var country = $("#country").val();
          let logo = new FormData(document.getElementById("addEditBookForm"));
          $("#btn-save").html('Please Wait...');
          $("#btn-save"). attr("disabled", true);
         
        // ajax
       
        $.ajax({
            type:"POST",
            url: "{{ url('admin/add-update-Airlines') }}",
            data: {
              id:id,
              name:name,
              country:country,
              logo:logo,
            },
            contentType: false,
            processData:false,
            cache: false,
            dataType: 'json',
            success: function(res){
             window.location.reload();
            $("#btn-save").html('Submit');
            $("#btn-save"). attr("disabled", false);
            Swal.fire(
            'Good job!',
            'You clicked the button!',
            'success'
            )
           }
        
        });
      
    });

Controller:

 public function store(Request $request)
    {
        

        $newImgName = time() . '-' . $request->name . '.' .$request->logo->extension();
        $request->logo->move(public_path('img'),$newImgName);
        $Airline   =   Airline::updateOrCreate(
                    [
                        'id' => $request->id
                    ],
                    $request->validate([
                        'name' => ['required', 'string', 'max:255'],
                        'country' => ['required', 'string', 'max:255'],
                        'logo' => ['required|mimes:ipg,png,jpeg|max:5048'],            
                    ]),
                   
                    [
                        'name' => $request->name, 
                        'country' => $request->country,
                        'logo' => $newImgName,
                    ]);
    
                 return response()->json(['success' => true]);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

相对绾红妆 2025-01-24 01:44:25

首先是 csrf 令牌没有传递给 ajax,所以更改形式如下。也更新了

<form action="{{ url('admin/add-update-Airlines') }}" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
         @csrf
            <input type="hidden" name="id" id="id">
            <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Name</label>
                <div class="col-sm-12">
                    <input type="text" class="form-control" id="name" name="name" placeholder="Enter Airline Name" value="" maxlength="50" required="">
                </div>
            </div>
            <div class="form-group">
                <label for="name" class="col-sm-2 control-label">country</label>
                <div class="col-sm-12">
                    <input type="text" class="form-control" id="country" name="country" placeholder="Enter Airline country" value="" maxlength="50" required="">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">Logo</label>
                <div class="col-sm-12">
                    <input type="file" class="form-control" id="logo" name="logo" placeholder="Enter Airline Code" value="" required="">
                </div>
            </div>
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary" id="btn-save" value="addNewBook">Save changes
                </button>
            </div>
        </form>

然后在 ajax 中我简化了测试,以便您可以根据需要进行修改

$(document).on('click', '#btn-save', function(e) {
            e.preventDefault()
            var url = $("#applicationForm").attr('action');
            let myForm = document.getElementById('addEditBookForm');
            let formData = new FormData(myForm);
            $.ajax({
                type:"POST",
                url:url,
                data: formData,
                contentType: false,
                processData:false,
                cache: false,
                dataType: 'json',
                success: function(res){

                }

            });

        });

验证

public function store(Request $request)
{
        
   $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'country' => ['required', 'string', 'max:255'],
            'logo' => ['required','mimes:ipg,png,jpeg','max:5048'],
        ]);
}

First thing is csrf token not passing to ajax so change form as below.Also updated

<form action="{{ url('admin/add-update-Airlines') }}" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
         @csrf
            <input type="hidden" name="id" id="id">
            <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Name</label>
                <div class="col-sm-12">
                    <input type="text" class="form-control" id="name" name="name" placeholder="Enter Airline Name" value="" maxlength="50" required="">
                </div>
            </div>
            <div class="form-group">
                <label for="name" class="col-sm-2 control-label">country</label>
                <div class="col-sm-12">
                    <input type="text" class="form-control" id="country" name="country" placeholder="Enter Airline country" value="" maxlength="50" required="">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">Logo</label>
                <div class="col-sm-12">
                    <input type="file" class="form-control" id="logo" name="logo" placeholder="Enter Airline Code" value="" required="">
                </div>
            </div>
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary" id="btn-save" value="addNewBook">Save changes
                </button>
            </div>
        </form>

Then in ajax I have simplified for testing so you can modify according to your need

$(document).on('click', '#btn-save', function(e) {
            e.preventDefault()
            var url = $("#applicationForm").attr('action');
            let myForm = document.getElementById('addEditBookForm');
            let formData = new FormData(myForm);
            $.ajax({
                type:"POST",
                url:url,
                data: formData,
                contentType: false,
                processData:false,
                cache: false,
                dataType: 'json',
                success: function(res){

                }

            });

        });

Validation

public function store(Request $request)
{
        
   $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'country' => ['required', 'string', 'max:255'],
            'logo' => ['required','mimes:ipg,png,jpeg','max:5048'],
        ]);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文