0

I'm trying to upload a file using Laravel and Dropzone.js as friendly UI.

According to the Enyo's tutorial and the official documentation and this tutorial in Spanish this one and that one. But I just can't figure out why I can't receive in the request Object the files that I'm actually trying to upload.

My code looks like this:

My view:

<div class="box-body">
{!! Form::open(['url' => '/admin/noticias', 'files' => true], ['id' => 'form' ]) !!}
<div class="form-group {{ $errors->has('file_gallery') ? 'has-error' : ''}}">
    {!! Form::label('File', 'Arrastre fotos a esta área') !!}
    <div class="row">
        <div class="col-md-10">
            <input class="file" name="file[]" type="file" id="file" multiple/>

            <div id="mydropzone" class="dropzone">
                <!--Sector de arrastre-->
            </div>

            {!! $errors->first('file', '<p class="help-block">:message</p>') !!}
        </div>
    </div>
</div>
<button id='btn_submit' type="submit" class="btn btn-primary"><i class="fa fa-fw fa-save"></i>Save</button>{{ Form::close() }} <script type="text/javascript" src="{{asset('js/jquery-ui-1.11.4/jquery-ui.js')}}"></script>

<link rel="stylesheet" href="{{asset('js/dropzone/dropzone.css')}}">
<script type="text/javascript" src="{{asset('js/dropzone/dropzone.js')}}"></script>


<script type="text/javascript">
    $('#datepicker_ini').datepicker({
        language: 'es',
        autoclose: true
    });

    $(function () {
        Dropzone.autoDiscover = false;
        $("div#mydropzone").dropzone({
            // method: 'GET',
            url: '{{route('admin.noticias.upload_gallery')}}',
            paramName: "file_gallery",
            autoProcessQueue: false,
            uploadMultiple: false,
            addRemoveLinks: true,
            parallelUploads: 10,
            maxFilesize: 10,
            acceptedFiles: ".jpeg,.jpe,.jpg,.png,.gif,.svg",
            dictRemoveFile: 'Remover foto',
            dictDefaultMessage: "Arrastre las fotos que desea subir aquí.",
            dictFallbackMessage: "Tu navegador no soporta arrastrar y soltar fotos",
            dictFallbackText: "Por favor, use el boton de seleccionar fotos",
            dictInvalidFileType: "No puedes subir archivos de este tipo.",
            dictCancelUpload: "Cancelar subida",
            dictCancelUploadConfirmation: "¿Está seguro que quiere cancelar esta subida?",
            dictMaxFilesExceeded: "No puedes subir más archivos.",

            success: function (file, response, data) {

                $('#galeria').empty(); // supongo que esto resetea los archivos guardados

                var rows = $('div#mydropzone').children('.dz-image-preview').get();
                $.each(rows, function (index, row) {
                    // Agregar cada elemento a #galeria[]
                });
            },
            removedfile: function (file) {
                x = confirm('¿Desea remover esta foto?');
                if (!x) return false;
                file.previewElement.remove();

                $('#galeria').empty(); // supongo que esto resetea los archivos guardados

                var rows = $('div#mydropzone').children('.dz-image-preview').get();
                $.each(rows, function (index, row) {
                });

            },
            init: function () {
                var myDropzone = this;
                this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    myDropzone.processQueue();
                });
            },
            accept: function(file) {
                let fileReader = new FileReader();

                fileReader.readAsDataURL(file);
                fileReader.onloadend = function() {

                    let content = fileReader.result;
                    $('#galeria').val(content);
                    file.previewElement.classList.add("dz-success");
                }
                file.previewElement.classList.add("dz-complete");
            }
        }).sortable({
            items: '.dz-preview',
            cursor: 'move',
            opacity: 0.5,
            containment: "parent",
            distance: 20,
            tolerance: 'pointer',
            update: function (e, ui) {

                $('#galeria').empty();
                var rows = $('div#mydropzone').children('.dz-image-preview').get();
                $.each(rows, function (index, row) {
                    // añadir al input #galeria
                });
            }
        });
    });

My Controller looks like this

NewsController.php

public function store(Request $request)
{
    dd($request->file); // this returns null;
}

public function upload(Request $request)
{
    return response()->json(['success' => true], 200); // just did this, in order to provide an URL with a response
}

Why do I want to save it like with a request form, it's because I'm using the Medialibrary package (which is actually pretty good).

TL;DR What am I trying to do? I'm trying to upload with a friendly UI, and save the image with the Medialibrary package with a request POST form.

What I've done so far : I've been able to sort the images, but when I click the submit button, $request->file_galery is null. I don't know why.

What is my purpose: I want to make a friendly UI, in which an user will be available to upload, sort, delete some of them (edit), remove all. In order to do that, I have added Medialibrary to my project for the backend, and Dropzone for the frontend.

Any help is appreciated.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
mito
  • 61
  • 8

1 Answers1

0

Here's what I did

In my footer, I added <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js" async></script>

Here's my form

<form action="/upload-image"
    class="dropzone w-100"
    id="my-awesome-dropzone">
    {{csrf_field()}}
</form>

In my Route

Route::post('/upload-image', [
    'uses' => 'MyController@uploadImages',
    'as' => 'my_controller.uploadImages'
]);

And my Controller function to upload the images

public function uploadImages(Request $request)
    {
        $image = $request->file('file');

        if($image) {
            $filenamewithextension = $request->file('file')->getClientOriginalName();

            //get filename without extension
            $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);

            //get file extension
            $extension = $request->file('file')->getClientOriginalExtension();

            //filename to store
            $filenametostore = $filename.'_'.time().'.'.$extension;

            Storage::disk('s3_driver')->put($filenametostore, fopen($request->file('file'), 'r+'), 'public');

            //do something with $filenametostore

            return "something";
        }
        else {
            return 'Fail';
        }
    }
Sam Bellerose
  • 1,782
  • 2
  • 18
  • 43
  • and what does ```dd($request->file('file'));``` shows? What are your dropzone options? – mito Nov 29 '18 at 13:48