Error loading image with Dropzone js in Laravel?

1

Cordial greeting colleagues, I have the following problem, I am developing an application in which you can upload images and for that I use the dropzone js plugin, my problem is that when I upload the image I get the following error:

I'm instantiating dropzone on a div.

I attach the code of the view:

@extends('layouts.layout')

<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.css">



@section('contenido')

<div>

<p>Album: {{ $foto->id }}</p>

</div>
<form action="{{ route('fotos') }}" method="POST" enctype="multipart/form-data">

        {{ csrf_field() }}  

<div class="form-group">


//div que utilizo para el dropzone
<div class="dropzone">



</div>

<div class="form-group">

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

    </div>
</form>
</div>

@stop

Code where I initialize dropzone:

@push('scripts')

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.js"></script>






<script >




var myDropzone = new Dropzone('.dropzone', {

// Ruta especificada
url: '/fotos',

// con esta sentencia le decimos a dropzone que solo acepte archivos de imagen y con el * le decimos que acepte imagenes con cualquier extension
acceptedFiles: 'image/*',

// con esta sentencia le definimos a dropzone la restriccion de tamaño del archivo a subir en Mega Bytes
maxFilesize: 2,

// con esta sentencia restringimos la cantidad de archivos que se pueden subir
// maxFiles: 1,

paramName: 'photo',



headers: {

    // verificacion del token
    'X-CSRF-TOKEN': '{{ csrf_token() }}'

},

// esta sentencia cambia el mensaje por defecto que aparece en la caja de dropzone
dictDefaultMessage : 'Arrastra las imagenes aqui para subirlas'

});

myDropzone.on('error', function(file , res){

console.log(res);

});

// con esta sentencia le decimos a dropzone que no se active automaticamente, solo cuando le demos clic
Dropzone.autoDiscover = false;

</script>


@endpush

Route code established for the form:

Route::get('fotos','FotoController@upload')->name('fotos');

PhotoController upload function:

 public function upload(Request $request)
    {

        $file = $request->file('photo');
        $fileUrl = $file->store('public');

        return 'imagen guardada';



    }

Any idea what can be wrong?

    
asked by Kevin Burbano 23.05.2018 в 05:28
source

1 answer

0

Apparently it's just a problem of routes.

When using laravel routes in script it is not advisable to write only the route, you should always use (is what I recommend) a function of routes, which can be url() , route() and even for importing documents it is advisable to use functions such as: public_path() , Storage::get() or asset() .

Then apparently your problem lies in the inizaalizacion of your dropzone specifically in the route or url:

url: '/fotos',//esta linea estaria mal, lo digo sin probarlo solo por experiencia

It should be as follows:

url: '{{url("fotos")}}',

Or in every case how you have defined the ->name('fotos') in your route you can also call it with route .

url: '{{route("fotos")}}',

Another error seems to be the answer, many libraries adapt to a standard communication of answers, so it's time to start getting used to sending an answer with codes such as success and error .

In your case it will be something like this:

public function upload(Request $request)
{

    $file = $request->file('photo');
    $fileUrl = $file->store('public');
    // algunas cosas mas para saber si se subio correctamente y luego...
    if( $si_se_subio_correctamete ) {
        return Response::json('success', 200);
    } else {
        return Response::json('error', 400);
    }

}

Another problem is the confusion in the type of route, in your routes in get and in your form this post .

To upload your image correctly I recommend the following code:

    $file = Input::file('photo');//foto es tu variable de formulario

    $extension = File::extension($file['name']);
    $directory = path('public').'uploads/'.sha1(time());
    $filename = sha1(time().time()).".{$extension}";

    $upload_success = Input::upload('file', $directory, $filename);

    if( $upload_success ) {
        return Response::json('success', 200);
    } else {
        return Response::json('error', 400);
    }

I hope it helps you.

    
answered by 23.05.2018 / 14:57
source