christopher's avatar

Dropzone save pictures in the database

This is my little upload code, all images will be uploaded to the album directory of the user.

Route::post('/upload', function () {

    $input = Input::all();

    $rules = array(
        'file' => 'image|max:3000',
    );

    $validation = Validator::make($input, $rules);

    if ($validation->fails())
    {
        return Response::make($validation->errors->first(), 400);
    }

    $file      = Input::file('file');
    $albumID   = Input::get('albumID');

    if($file) {

        $destinationPath = public_path() . '/uploads/' . $albumID ;
        $filename = $file->getClientOriginalName();

        $upload_success = Input::file('file')->move($destinationPath, $filename);

        if ($upload_success) {

            // resizing an uploaded file
            Image::make($destinationPath . $filename)->resize(100, 100)->save($destinationPath . "100x100_" . $filename);

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

So far it`s working with the upload, but how can i now save all images (path) to my database table too ?

0 likes
17 replies
christopher's avatar

No ideads how i can store multiple files to my database table ?

christopher's avatar

Yep .. but i`m getting a 500er error every time ( one image ). This is my currently upload code.

I created an Image Model with

    public function album() {
        //return $this->belongsToMany('Museums', 'id');
        return $this->belongsTo('Album');
    }

In my Album Model i have

    public function image() {
        //return $this->belongsToMany('Museums', 'id');
        return $this->hasMany('Image');
    }

My Upload Method

Route::post('/upload', function () {

    $input = Input::all();

    $rules = array(
        'file' => 'image|max:3000',
    );

    $validation = Validator::make($input, $rules);

    if ($validation->fails())
    {
        return Response::make($validation->errors->first(), 400);
    }

    $file = Input::file('file');
    $albumID = Input::get('albumID');
    $museumName = Input::get('museumName');

    if($file) {

        $destinationPath = public_path() . '/uploads/'.$museumName . '/' . $albumID.'/';
        $filename = $file->getClientOriginalName();

        $upload_success = Input::file('file')->move($destinationPath, $filename);

        if ($upload_success) {

            // resizing an uploaded file
            Image::make($destinationPath . $filename)->resize(100, 100)->save($destinationPath . "100x100_" . $filename);

            $image = New Image();
            $image->title = $filename;
            $image->path = $destinationPath;
            $image->album_id = $albumID;
            $image->save();

            return Response::json('success', 200);
        } else {
            return Response::json('error', 400);
        }
    }
});
christopher's avatar

Im getting only a 500er error in my debug console. Because its via ajax i dont get a specific laravel error

bashy's avatar

Check the network tab and view the response from that POST request

Like the POST for this reply below (obviously not response for this one)

1 like
Felix's avatar

Click on 'upload' and show the response.

1 like
christopher's avatar

That is the Response of the upload - There is no "upload button" because you drag and drop the image into dropzone. Dropzone then automatically uploads the picture without pressing any button. -> http://www.dropzonejs.com/

bashy's avatar

All a button does is POST the form, Dropzone JS just does it for you, just post the response for the error or check the logs.

1 like
christopher's avatar

This is the Reponse error

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Call to undefined method Intervention\\Image\\Facades\\Image::save()","file":"\/home\/vagrant\/code\/museum\/app\/routes.php","line":233}}

Line 233 is

            $image->save();
christopher's avatar

So there is a conflict between ?

Image::make ...

and

$image = New Image();

What should i write and where should i write it to naming the alias ? Because stack: Where do i have to put this ?

'Img' => 'Intervention\Image\Facades\Image'
bashy's avatar

app/config/app.php? You should of already added that in once already

1 like
christopher's avatar

You`re fucking awesome ! :P I should pay you for all your help :) :) Thank you so much

Now all is working with dropzone !

bashy's avatar

I enjoy helping, glad you got it sorted!

Remember to use the dev tools on Chrome, they'll help you find errors faster and easier. The Network tab in insanely helpful for HTTP requests.

nitinsridar's avatar
@script

var baseUrl = "{{ url('/') }}"; var token=$('#token').val(); Dropzone.autoDiscover = false; var myDropzone = new Dropzone("div#dropzoneSiteImages", { url: "your_Url_to_controller or route", params: { _token: token }, maxFiles:50, init: function() { this.on("maxfilesexceeded", function(file){ this.removeFile(file); alert("Maximum 50 photos are allowed...!"); });

    this.on("addedfile", function (file) {
      var removeButton = Dropzone.createElement("<button><i class='glyphicon glyphicon-trash'></i></button>");
      var _this = this;
      removeButton.addEventListener("click", function (e){
        e.preventDefault();
        e.stopPropagation();
        _this.removeFile(file);

        console.log('ADDED');

        var i=0;
        var found=0;
        var len = Object.keys(image_array).length;
        for(i=0;i<len;i++){

          if(image_array.hasOwnProperty(i)){
            if(image_array[i]['name'] == file.name){

              $.ajax({
                type: 'GET',
                url:'{{URL::route("deleteImages")}}',
                dataType: 'json',
                data:{path:image_array[i]['file_path']},
                async:false
              }).done(function(result1){

                image_array[i]['name']=undefined;
                image_array[i]['file_path']=undefined;
                return;

              });

              found==1;
              break;
            }
            if(found==1){
              break;
            }
          }
          if(found==1){
            break;
          }

        }

        $('#image_array').val(JSON.stringify(image_array));

      });
      file.previewElement.appendChild(removeButton);
    });

    this.on("success", function(file,responseText){

      console.log('responseTexTTTTTTT');
      console.log(responseText['file']);

      image_array[image_i]={};   // Put your image_array as hidden
      image_array[image_i]['file_path']=responseText['file'];
      image_array[image_i]['name']=file.name;
      image_i++;


      $('#image_array').val(JSON.stringify(image_array));
    });

  },

});

Please or to participate in this conversation.