且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用表单数据上载Ajax文件Laravel 5.3

更新时间:2022-10-21 14:53:09

Try using the FormData in ajax while you upload a file.

Just try this

$('form').submit(function(event) {
    event.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
        url: '{{ url('/agents') }}',
        type: 'POST',              
        data: formData,
        success: function(result)
        {
            location.reload();
        },
        error: function(data)
        {
            console.log(data);
        }
    });

});

OR

You can try with this jQuery library

https://github.com/malsup/form

EDIT

public function store(Request $request)
{
    if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
       return $this->respondBadRequest('Phone Number Exists');
    }
    else 
    {
        $user=User::create($request->all());

        if($request->hasFile('image')) {
           $file = $request->file('image');

           //you also need to keep file extension as well
           $name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();

           //using array instead of object
           $image['filePath'] = $name;
           $file->move(public_path().'/uploads/', $name);
           $user->image= public_path().'/uploads/', $name;
           $user->save();
        }
        return redirect('agents')->with('Success', 'Agent Added');
    }
}

相关阅读

技术问答最新文章