Ajax File Upload With Form Data Laravel 5.3
Answer :
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'); } }
Try something like this:
$('#upload').on('click', function() { var file_data = $('#pic').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); $.ajax({ url : 'route_url', dataType : 'text', // what to expect back from the PHP script, if anything cache : false, contentType : false, processData : false, data : form_data, type : 'post', success : function(output){ alert(output); // display response from the PHP script, if any } }); });
Just me or does your <input type="file">
not have a "name" attribute? Therefore the server is not receive the file data from the post?
EDIT:
After you insert the record into the database, you then handle the file uploading - but you never then update the record with the files name.
*Just confirm that the file was uploaded.
Comments
Post a Comment