Search code examples
phpajaxlaravelmove

Laravel ajax image upload 'move' function creating 500 error


I am trying to do an AJAX image upload with Laravel 5.4. All the other fields in my form is working except for the move() function on the file input, which returns a 500 error. I have added all the code related to the image below. When the submit button is clicked I am doing e.preventDefault() and then starting the ajax function.

HTML

{!! Form::open(['action' => 'ProjectController@store','id' => 'createForm','files' => true]) !!}
    <div class="form-group">
        {!! Form::label('image', 'Project Image') !!}
        {!! Form::file('image') !!}
    </div>
    {!! Form::submit('Create', ['id' => 'createSubmit', 'class' => 'btn btn-primary']) !!}
{!! Form::close() !!}

AJAX

var formData = new FormData($('#formElem'));    
$.ajax({
        url: '{{ route('project.store') }}',
        type: 'post',
        contentType: false,
        processData: false,
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        data: formData,
        success: function(data) {
            alert('success');
        },
        error: function(data) {
            alert('error');
            console.log(data);
        }
    });

PHP

if (isset($_FILES['image'])) {
    $image = $_FILES['image'];
    $image_filename = 'feature-' . $image['name'];
    // THIS LINE CAUSES THE 500 ERROR
    // $image->move(public_path('uploads'), $image_filename);
}

VAR_DUMP OF $_FILES['image']

array(5) {
  ["name"]=>
  string(12) "Homepage.png"
  ["type"]=>
  string(9) "image/png"
  ["tmp_name"]=>
  string(23) "C:\xampp\tmp\php7AD.tmp"
  ["error"]=>
  int(0)
  ["size"]=>
  int(251159)
}

The uploads folder does exist.


Solution

  • Try upload image like this :

    $destinationPath = 'path/th/save/file/';
    $image = $request->file('image');
    $name =  $user_meta['image_org_name'] = $image->getClientOriginalName();
    $extension = $image->getClientOriginalExtension();
    $file_name =  md5(uniqid().time()).'_'.$user_meta['image_org_name'];
    $image->move($destinationPath,$file_name);