Ajax File Upload With Form Data Laravel 5.3

后端 未结 5 1739
迷失自我
迷失自我 2020-12-28 21:48

i want to upload a profile image of a user to the server and i\'m stuck at ajax upload of image

all my form data are posting to datab

5条回答
  •  有刺的猬
    2020-12-28 22:44

    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 the 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');
        }
    }
    

提交回复
热议问题