Hello, I need to add an image via ajax, but I cannot accept the file (returns null), please tell me what I'm doing wrong.

ajax:

var form_data = new FormData('img', img_file.prop('files')[0]); $.ajax({ type: "POST", //Метод отправки url: "/upload_image", //путь до php фаила отправителя processData: false, dataType: 'json', data: form_data, success: function(success) { console.log(success) form_data = undefined; console.log('zbs' + form_data) } }); 

Controller:

 public function upload_product_image(Request $request){ $key = $request->key; $picture = Input::file("img"); return response()->json(['picture' => $picture]); } 

Another question: how to simultaneously transfer other variables with the file?

  • HTML form show for full understanding - Yaroslav Molchan
  • form_data.append(name, value); - Orange_shadow

1 answer 1

Personally, I have

 $('#image').change(function () { var formData = new FormData(); formData.append('avatar', $('#image')[0].files[0]); $.ajax({ url: '/api/uploadAvatar', type: 'POST', data: formData, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success: function (data) { d = new Date(); $("#avatar").attr("src", data.file+"?"+d.getTime()); } }); }); 

Here is the controller

 public function uploadAvatar(Request $request) { $request->validate([ 'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg', ]); $user = Auth::user(); $imageName = $user->id . '.' . $request->avatar->getClientOriginalExtension(); $mv = $request->avatar->move(public_path('avatars'), $imageName); $user->avatar = url('avatars', $imageName); $user->save(); $response = [ 'status' => 'success', 'message' => "Картинка профиля загружена", 'file' => url('avatars', $imageName) ]; return response()->json($response); }