使用Dropzone和Laravel

时间:2017-12-19 07:58:51

标签: laravel laravel-5 dropzone.js dropzone

我正在尝试创建一个页面,用户可以在其中添加标题,然后上传图像或2.我正在使用dropzone和Laravel,我试图让它看起来与众不同, 我让它看起来像http://www.dropzonejs.com/bootstrap.html

我遇到的问题是我需要在js文件中添加一个url,但它一直给我这个错误

  

POST http://crud.test/portfolios 419(未知状态)

并在我的开发工具预览中

  

{message:“”,exception:“Symfony \ Component \ HttpKernel \ Exception \ HttpException”,...}

我知道在Laravel中我会使用

{{ csrf_field() }}

我无法将我的图像上传到我在控制器中指定的文件夹或将图像保存到我的数据库。

我想要的是如何将我的图片上传到该文件夹​​并保存到我的数据库中。

我的刀片:

<form action="{{ route('portfolios.store') }}">
    {{ csrf_field() }}

    <div class="form-group">
        <label>Title</label>
        <input type="title" name="title" class="form-control">
    </div>

    <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 files...</span>
            </span>

            <button type="button" class="btn btn-info start">
                <i class="glyphicon glyphicon-upload"></i>
                <span>Start upload</span>
            </button>

            <button type="reset" class="btn btn-warning cancel">
                <i class="glyphicon glyphicon-ban-circle"></i>
                <span>Cancel upload</span>
            </button>
        </div>

        <div class="col-lg-5">
            <span class="fileupload-process">
                <div id="total-progress" class="progress progress-striped active total-upload-progress" 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>
            </span>
        </div>
    </div>

    <div class="table table-striped files" id="previews">
        <div id="template" class="file-row dz-image-preview">
            <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-info 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>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

我的main.js:

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: "/portfolios", // Set the url
    thumbnailWidth: 80,
    thumbnailHeight: 80,
    parallelUploads: 20,
    previewTemplate: previewTemplate,
    autoQueue: false, // Make sure the files aren't queued until manually added
    uploadMultiple: true,
    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) {
    file.previewElement.querySelector(".start").onclick = function() { 
        myDropzone.enqueueFile(file); 
    };
});

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

myDropzone.on("sending", function(file) {
    document.querySelector("#total-progress").style.opacity = "1";
    file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});

myDropzone.on("queuecomplete", function(progress) {
    document.querySelector("#total-progress").style.opacity = "0";
});

document.querySelector("#actions .start").onclick = function() {
    myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
};

document.querySelector("#actions .cancel").onclick = function() {
    myDropzone.removeAllFiles(true);
};

我的控制器:

public function store(Request $request)
{
    $portfolio = new Portfolio();

    $portfolio->fill($this->getSafeInput($request));

    if($request->hasFile('file'))
    {
        $names = [];
        foreach($request->file('file') as $image)
        {

            $destinationPath = 'portfolio_images/';
            $filename = $image->getClientOriginalName();
            $image->move($destinationPath, $filename);
            array_push($names, $filename); 
        }

        $portfolio->file = json_encode($names);
    }

    $portfolio->save();

    return redirect()->route('portfolios.index');
}

我的路线:

Route::get('/', function () {
    return view('welcome'); 
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::resource('/portfolios', 'PortfolioController');

我希望我已经正确解释,如果我留下任何信息,请告诉我

2 个答案:

答案 0 :(得分:4)

问题是Dropzone会在您删除文件时自动POST。但它不包括它POST的请求中的任何其他字段 - 只是文件。因此缺少您的CSRF令牌(与表单上的所有其他字段一样),并且Laravel会抛出错误。

有几种方法可以解决这个问题。这里最简单的方法是将CSRF令牌添加到sending()偶数处理程序中POST的数据中。 Dropzone docs even mention doing exactly this

  

...您可以修改它们(例如添加CSRF令牌)......

所以,在你的代码中:

// First, include the 2nd and 3rd parameters passed to this handler
myDropzone.on("sending", function(file, xhr, formData) {

    // Now, find your CSRF token
    var token = $("input[name='_token']").val();

    // Append the token to the formData Dropzone is going to POST
    formData.append('_token', token);

    // Rest of your code ...
    document.querySelector("#total-progress").style.opacity = "1";
    file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});

请注意,您的CSRF令牌(表单上仍然保持不变)现在无效 - 刚刚处理的POST请求意味着它已更新。您删除的下一个文件将重复使用相同的令牌,但它将失败。

更完整的解决方案是完全禁用文件发送,直到您点击提交按钮,然后立即发送所有文件和所有表单字段。为此,您必须disable autoProcessQueue

autoProcessQueue = false,

接下来,由于队列未进行自动处理,因此您现在必须在提交表单时手动处理它by firing processQueue()。在提交表单时,您需要触发某种事件处理程序:

// Event handler to fire when your form is submitted
$('form').on('submit', function(e) {
    // Don't let the standard form submit, we're doing it here
    e.preventDefault();

    // Process the file queue
    myDropzone.processQueue();
});

最后,您需要将表单中的CSRF令牌添加到数据Dropzone将POST:

myDropzone.on("sending", function(file, xhr, formData) {

    // Find all input values on your form
    var data = $('form').serializeArray();

    // Append them all to the formData Dropzone will POST
    $.each(data, function(key, el) {
        formData.append(el.name, el.value);
    });

    // Rest of your code ...
    document.querySelector("#total-progress").style.opacity = "1";
    file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});

答案 1 :(得分:0)

您的表单缺少文件updload的enctype,enctype属性指定在将表单数据提交到服务器时应如何编码表单数据。所以将该属性添加到表单中:

<form action="/action_page_binary.asp" method="post" enctype="multipart/form-data">

adn也将该方法指定为post!