num3thod's avatar

Intervention image upload - ajax post problem

Hi, I've been banging my head for hours now trying to figure out why Laravel doesn't seem to get the ajax post data for a file upload.

Specifically, Laravel seems to be unable to "read" the posted object data. Or, at least, I'm going about it the wrong way.

My approach: 1- retrieve the file object 2- post to laravel 3- save file and return success message (pretty simple stuff)

My code:

//JS
uploadElement.on("drop", function (e) {
   e.preventDefault();
   var file = e.originalEvent.dataTransfer.files[0];
   handleFileUpload(file);
});

function handleFileUpload(file) {
   var form = new FormData();
   form.append('file', file);
   $.post('upload', {
      data: form
   }, onSuccess);
}

function onSuccess(data, status, xhr) {
   console.log(data, status, xhr);
}
//PHP
Route::post('upload', function(){
   if (Request::ajax()) {
      $data = Input::get('file');
      if (Input::hasFile('file'))
      {
         $file = Input::file('file');
         $file->move('public/uploads', 
         $file->getClientOriginalName());
         $image = Image::make(sprintf('public/uploads/%s', $file->getClientOriginalName()))->resize(200, 200)->save();
         return "YES F**K YES!";
         }
      return $data;
      //returns "[]" for some reason
   }
});

I am getting a http 200 from the laravel post handler. Just not getting into the if (Input::hasFile('file')) condition.

Any help or insight or even vaguest of hints would be greatly appreciated.

Thanks,

MR

0 likes
1 reply
num3thod's avatar
num3thod
OP
Best Answer
Level 4

Solved by ditching $.post and replace with a proper $.ajax call. So umm, $.post sucks.

Hehe, you can Askers's Choice yourself. Whoda thunk it?

Please or to participate in this conversation.