Laravel 5.1和DropzoneJS 4.2无法上传照片

时间:2015-11-27 18:40:07

标签: laravel dropzone.js

我正在使用Laravel 5.1和DropzoneJS 4.2上传图片,我复制了这个例子的代码http://www.dropzonejs.com/bootstrap.html,and修改了它。 enter image description here

单击开始按钮,无法发送http请求。

这是我的意思:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css">

    <style>
        html, body {
            height: 100%;
        }

        #actions {
            margin: 2em 0;
        }

        /* Mimic table appearance */
        div.table {
            display: table;
        }

        div.table .file-row {
            display: table-row;
        }

        div.table .file-row > div {
            display: table-cell;
            vertical-align: top;
            border-top: 1px solid #ddd;
            padding: 8px;
        }

        div.table .file-row:nth-child(odd) {
            background: #f9f9f9;
        }

        /* The total progress gets shown by event listeners */
        #total-progress {
            opacity: 0;
            transition: opacity 0.3s linear;
        }

        /* Hide the progress bar when finished */
        #previews .file-row.dz-success .progress {
            opacity: 0;
            transition: opacity 0.3s linear;
        }

        /* Hide the delete button initially */
        #previews .file-row .delete {
            display: none;
        }

        /* Hide the start and cancel buttons and show the delete button */
        #previews .file-row.dz-success .start,
        #previews .file-row.dz-success .cancel {
            display: none;
        }

        #previews .file-row.dz-success .delete {
            display: block;
        }
    </style>
</head>
<body>

<div class="container" id="container">
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
        upload photos
    </button>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-dialog dropzone" id="my-awesome-dropzone" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                        <span class="sr-only">Close</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel">upload photos</h4>
                </div>
                <div class="modal-body">
                    <div id="actions" class="row">
                        <div class="col-lg-7">
                            <span class="btn btn-success fileinput-button dz-clickable">
                                 <i class="glyphicon glyphicon-plus"></i>
                                 <span>add photos</span>
                             </span>
                        </div>
                    </div>
                    <div class="table table-striped files" id="previews">
                        <div id="template" class="file-row">
                            <!-- This is used as the file preview template -->
                            <div><span class="preview"><img data-dz-thumbnail/></span></div>
                            <div>
                                <p class="name" data-dz-name></p>
                                <strong class="error text-danger" data-dz-errormessage></strong>
                            </div>
                            <div>
                                <p class="size" data-dz-size></p>

                                <div class="progress progress-striped active" role="progressbar"
                                     aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
                                    <div class="progress-bar progress-bar-success" style="width:0%;"
                                         data-dz-uploadprogress></div>
                                </div>
                            </div>
                            <div>
                                <button class="btn btn-primary start">
                                    <i class="glyphicon glyphicon-upload"></i>
                                    <span>Start</span>
                                </button>
                                <button data-dz-remove class="btn btn-warning cancel">
                                    <i class="glyphicon glyphicon-ban-circle"></i>
                                    <span>Cancel</span>
                                </button>
                                <button data-dz-remove class="btn btn-danger delete">
                                    <i class="glyphicon glyphicon-trash"></i>
                                    <span>Delete</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>
    <script src="http://ajax.useso.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js"></script>
    <script src="https://cdn.bootcss.com/dropzone/4.2.0/min/dropzone.min.js"></script>
</body>
</html>

这是剧本:

<script>
    Dropzone.autoDiscover = false;
</script>
<script>
    // Get the template HTML and remove it from the doument
    var previewNode = document.querySelector("#template");
    previewNode.id = "";
    var previewTemplate = previewNode.parentNode.innerHTML;
    previewNode.parentNode.removeChild(previewNode);

    var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
        url: "fileupload", // Set the url
        thumbnailWidth: 80,
        thumbnailHeight: 80,
        parallelUploads: 20,
        previewTemplate: previewTemplate,
        autoQueue: false, // Make sure the files aren't queued until manually added
        previewsContainer: "#previews", // Define the container to display the previews
        clickable: ".fileinput-button" // Define the element that should be used as click trigger to select files.
    });

    myDropzone.on("addedfile", function (file) {
        // Hookup the start button
        file.previewElement.querySelector(".start").onclick = function () {
            myDropzone.enqueueFile(file);
        };
    });

    // Update the total progress bar
    myDropzone.on("totaluploadprogress", function (progress) {
        document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
    });

    myDropzone.on("sending", function (file) {
        // Show the total progress bar when upload starts
        document.querySelector("#total-progress").style.opacity = "1";
        // And disable the start button
        file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
    });

    // Hide the total progress bar when nothing's uploading anymore
    myDropzone.on("queuecomplete", function (progress) {
        document.querySelector("#total-progress").style.opacity = "0";
    });

    // Setup the buttons for all transfers
    // The "add files" button doesn't need to be setup because the config
    // `clickable` has already been specified.
    document.querySelector("#actions .start").onclick = function () {
        myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
    };
    document.querySelector("#actions .cancel").onclick = function () {
        myDropzone.removeAllFiles(true);
    };
</script>

这是路线:

Route::resource('fileupload', 'FileController');

这些是控制器:

public function imageUpload(Requests\StorePhotoPostRequest $request)
{
    $this->wrongTokenAjax();
    $file = \Input::file('file');
    $destinationPath = 'uploads/';
    $extension = $file->getClientOriginalExtension();
    $fileName = \Auth::user()->id . '_' . time() . '.' . $extension;
    $upload_success = \Input::file('file')->move($destinationPath, $fileName);
    if ($upload_success) {
        return \Response::json('success', 200);
    } else {
        return \Response::json('error', 400);
    }
}

public function wrongTokenAjax()
{
    if (\Session::token() !== \Request::get('_token')) {
        $response = [
            'status' => false,
            'errors' => 'Wrong Token',
        ];

        return \Response::json($response);
    }

}

这是请求:

public function rules()
{
    return [
       'file' => 'required|image(jpeg,jpg,png,bmp,gif)',
    ];
}

1 个答案:

答案 0 :(得分:1)

我认为问题在于您没有通过上传发送CSRF令牌。

首先在<head>

中添加CSRF令牌
<meta name="csrf_token" content="{{ csrf_token() }}">

尝试替换此

myDropzone.on("sending", function (file) {
        // Show the total progress bar when upload starts
        document.querySelector("#total-progress").style.opacity = "1";
        // And disable the start button
        file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
    });

有了这个:

myDropzone.on("sending", function (file, xhr, formData) {
        formData.append("_token", $('[name="csrf_token"]').attr('content')); 
    });