erfan_atp's avatar

How to upload file via ajax in L5

Hi. I need to upload file via ajax. But I can't find a clear tutorial for this.Can anybody help me? I have used jQuery-File-Upload plugin ( https://github.com/blueimp/jQuery-File-Upload ) but it was not helpful.

0 likes
3 replies
Aeonax's avatar

Why was it not helpful for you? I'm using jQuery File Upload and it works fine. Takes a bit to hack together your own interface and having it look nice if you don't want to start from one of the defaults but it works well.

erfan_atp's avatar

This is my HTML:

<!-- The fileinput-button span is used to style the file input field as button -->
    <span class="btn btn-success fileinput-button">
            <i class="glyphicon glyphicon-plus"></i>
            <span>Add files...</span>
            <!-- The file input field used as target for the file upload widget -->
            <input id="fileupload" type="file" name="files[]" multiple>
            <input type="hidden" class="hidden-token" name="_token" value="{!! csrf_token() !!}">
        </span>
    <br>
    <br>
    <!-- The global progress bar -->
    <div id="progress" class="progress">
        <div class="progress-bar progress-bar-success"></div>
    </div>
    <!-- The container for the uploaded files -->
    <div id="files" class="files"></div>

and this is my script:

/*jslint unparam: true, regexp: true */
        /*global window, $ */
        $(function () {
            'use strict';
            // Change this to the location of your server-side upload handler:
            var url = window.location.hostname === 'blueimp.github.io' ?
                            '//jquery-file-upload.appspot.com/' : 'server/php/',
                    uploadButton = $('<button/>')
                            .addClass('btn btn-primary')
                            .prop('disabled', true)
                            .text('Processing...')
                            .on('click', function () {
                                var $this = $(this),
                                        data = $this.data();
                                $this
                                        .off('click')
                                        .text('Abort')
                                        .on('click', function () {
                                            $this.remove();
                                            data.abort();
                                        });
                                data.submit().always(function () {
                                    $this.remove();
                                });
                            });
            $('#fileupload').fileupload({
                url: '/upload/artist/image',
                method: 'post',
                dataType: 'json',
                autoUpload: false,
                formData: {_token: $('.hidden-token').val()},
                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                maxFileSize: 5000000, // 5 MB
                // Enable image resizing, except for Android and Opera,
                // which actually support image resizing, but fail to
                // send Blob objects via XHR requests:
                disableImageResize: /Android(?!.*Chrome)|Opera/
                        .test(window.navigator.userAgent),
                previewMaxWidth: 100,
                previewMaxHeight: 100,
                previewCrop: true,
                success: function(){
                  alert('ok');
                },
                error: function(){
                    alert('fuck');
                },
            }).on('fileuploadadd', function (e, data) {
                data.context = $('<div/>').appendTo('#files');
                $.each(data.files, function (index, file) {
                    var node = $('<p/>')
                            .append($('<span/>').text(file.name));
                    if (!index) {
                        node
                                .append('<br>')
                                .append(uploadButton.clone(true).data(data));
                    }
                    node.appendTo(data.context);
                });
            }).on('fileuploadprocessalways', function (e, data) {
                var index = data.index,
                        file = data.files[index],
                        node = $(data.context.children()[index]);
                if (file.preview) {
                    node
                            .prepend('<br>')
                            .prepend(file.preview);
                }
                if (file.error) {
                    node
                            .append('<br>')
                            .append($('<span class="text-danger"/>').text(file.error));
                }
                if (index + 1 === data.files.length) {
                    data.context.find('button')
                            .text('Upload')
                            .prop('disabled', !!data.files.error);
                }
            }).on('fileuploadprogressall', function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css(
                        'width',
                        progress + '%'
                );
            }).prop('disabled', !$.support.fileInput)
                    .parent().addClass($.support.fileInput ? undefined : 'disabled');
        });
    </script>

in my routes.php :

Route::post('/upload/artist/image', function() {
        return view('upload.artist-image');
    });

and finally in artist-image.php I use this simple code:

return response()->json(['name' => 'Abigail', 'state' => 'CA']);

But in my ajax does not have any response even in console and network (chrome inspect element) and always my upload return fail text in this plugin.

Please or to participate in this conversation.