AJDEV
AJDEV

Reputation: 5740

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.

Upvotes: 0

Views: 628

Answers (2)

Pankaj Makwana
Pankaj Makwana

Reputation: 3050

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);

Upvotes: 1

Diego Poveda
Diego Poveda

Reputation: 120

What error are you getting, probably is something related to the permission of the 'uploads' folder?

Check the 500 error details on the Laravel logs.

You can also check the error details in the chrome Dev tool. Go to 'Network' tab, filter by 'XHR', click on the 500 error which should be highlighted in red, and on the top menu change to 'preview' tab. That should give u the detailed server error.

Upvotes: 2

Related Questions