如何通过Laravel 5中的ajax上传文件

时间:2015-05-17 08:08:25

标签: php jquery ajax laravel-5

我使用过jQuery-File-Upload插件(https://github.com/blueimp/jQuery-File-Upload),但没有帮助。 这是我的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>

和我的剧本:

/*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('error');
                },
            }).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>

我的routes.php:

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

最后在artist-image.php中我使用了这个简单的代码:

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

但是在我的ajax中,即使在控制台和网络(chrome检查元素)中也没有任何响应,并且我的上传总是返回此插件中的失败文本。

1 个答案:

答案 0 :(得分:5)

您无法通过(基本)AJAX(XMLHttpRequest)发送文件。

你需要使用一些“iframe”上传器或XMLHttpRequest2。 我会选择XHR2。

/**
 * Read selected files locally (HTML5 File API)
 */
var filesToUpload = null;

function handleFileSelect(event)
{
    var files = event.target.files || event.originalEvent.dataTransfer.files;
    // Itterate thru files (here I user Underscore.js function to do so).
    // Simply user 'for loop'.
    _.each(files, function(file) {
        filesToUpload.push(file);
    });
}

/**
 * Form submit
 */
function handleFormSubmit(event)
{
    event.preventDefault();

    var form = this,
        formData = new FormData(form);  // This will take all the data from current form and turn then into FormData

    // Prevent multiple submisions
    if ($(form).data('loading') === true) {
        return;
    }
    $(form).data('loading', true);

    // Add selected files to FormData which will be sent
    if (filesToUpload) {
        _.each(filesToUpload, function(file){
            formData.append('cover[]', file);
        });        
    }

    $.ajax({
        type: "POST",
        url: 'url/to/controller/action',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response)
        {
            // handle response
        },
        complete: function()
        {
            // Allow form to be submited again
            $(form).data('loading', false);
        },
        dataType: 'json'
    });
}

/**
 * Register events
 */
$('#file-input').on('change', handleFileSelect);
$('form').on('submit', handleFormSubmit);