user3089464
user3089464

Reputation: 251

Laravel 4.2 Input File Null

I have form for upload multiple image file combine with Laravel 4.2 and Ajax. But when uploaded image, input file always NULL. How can i fix it ?

This my Upload Form.

{{ Form::open(array('url' => route('member.font.upload.images'), 'files'=>true, 'id'=>'upload-images', 'method'=> 'post')) }}
    {{ Form::file('image[]', array('multiple'=>true, 'id'=>'images')) }}
    <input type="hidden" name="font" value="{{ $font->id }}">
{{ Form::close() }}

And Upload Process in Controller.

public function uploadImages()
{
$rules = array(
    'font' => 'required'
);

$validator = Validator::make(Input::all(), $rules);

if ($validator->fails()) {
    return Response::json(['success' => false, 'message' => 'Failed upload image']);
} else {
    if(Input::hasFile('image')){
        $images = Input::file('image');
        foreach($images as $image) {
            $imagename = time() . $image->getClientOriginalName();
            $upload =  $image->move('images/', $imagename);

            if($upload){
                $data = new Image;
                $data->font_id      = Input::get('font');
                $data->name         = $imagename;
                $data->save();
            }
        }
        return Response::json(['success' => true, 'message' => 'Success']);
    }else{
        return Response::json(['success' => false, 'message' => 'File not found']);
    }
}
}

And then Ajax process.

$('#images').change(function(e) {
e.preventDefault();
$.ajax({
    url: $('#upload-images').attr('action'),
    type: 'post',
    dataType: 'json',
    data: $('#upload-images').serialize(),
    beforeSubmit: function() {
        $('.add-images').removeClass('enabled').addClass('uploading');
    },
    success: function(data) {
        $('.add-images').removeClass('uploading').addClass('enabled');
    },
    error: function() {}
    });
});

Upvotes: 1

Views: 680

Answers (2)

Hamidreza Bayat
Hamidreza Bayat

Reputation: 103

You may need to define encoding type of the form.

{{ Form::open(array('url' => route('member.font.upload.images'), 'files'=>true, 'id'=>'upload-images', 'method'=> 'post', 'enctype' => "multipart/form-data")) }}

You can use this W3Schools doc to understand more details.

Upvotes: 1

Grald
Grald

Reputation: 464

Change this section:

{{ Form::open(array('url' => route('member.font.upload.images'), 'files'=>true, 'id'=>'upload-images', 'method'=> 'post')) }}

To:

{{ Form::open(array('route' => 'member.font.upload.images', 'files'=>true, 'id'=>'upload-images', 'method'=> 'post')) }}

Upvotes: 0

Related Questions