osherdo's avatar

Getting data from js to laravel (dropzone.js)

I have working image upload feature using 'dropzone.js` . What I need now is to associate the uploaded image to the authenticated user who uploads it, and store it in his personal folder of profile images.

By that, I have created models of 'User' and ProfileImage. I don't know how to catch the file upload from dropzone.js to Laravel, and how to proccess it then.

This is what I have so far: View:

    <div class="container">
                <div class="dropzone" id="dropzoneFileUpload">
                </div>
                <button type="button" id="uploadPhoto">Upload Photo</button>
                <!-- <form id="dropzoneFileUpload" method="post" action="{{action('DropzoneController@uploadFiles')}}" class="dropzone">
                  <div class="fallback">
                    <input name="file" type="file" />
                    <input type="hidden" name="_token" value="{{Session::getToken()}}">
                  </div>
                </form> -->
            </div>


          <script type="text/javascript">
                // var baseUrl = "{{ url('/') }}";
                // var token = "{{ Session::getToken() }}";
                Dropzone.autoDiscover = false;
                jQuery(document).ready(function(){



                   var myDropzone = new Dropzone("div#dropzoneFileUpload", {
                       url: "{{action('DropzoneController@uploadFiles')}}",
                       maxFilesize: 2, // MB
                           maxFiles: 1,
                           addRemoveLinks: true,
                       autoProcessQueue:false,
                       params: {
                          _token: "{{csrf_token()}}"
                        },

                   });

                     myDropzone.on("success", function(file,resp){
                       if(resp=="success"){
                         alert("Image uploaded successfully");
                       }
                       else {
                         alert("Faild to upload image! Try again");
                       }
                     });
                     
                    jQuery("button#uploadPhoto").click(function(){
                      myDropzone.processQueue();
                    });
                });
             </script>

Controller:

  public function index()
{
  return view('dropzone_demo');
}

public function uploadFiles()
{

  $message="Profile Image Created";
  $input = Input::all();

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

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

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

  $destinationPath = 'uploads'; // upload path: public/uploads
  $extension = Input::file('file')->getClientOriginalExtension(); // getting file extension
  $fileName = rand(11111, 99999) . '.' . $extension; // renameing image
  $upload_success = Input::file('file')->move($destinationPath, $fileName); // uploading file to given path

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

}

ProfileImage model:

class profile_image extends Model
{
    protected $table="profile_images";
}
0 likes
3 replies
mstnorris's avatar

See this tutorial https://maxoffsky.com/code-blog/howto-ajax-multiple-file-upload-in-laravel/

It was found on the dropzone js website. :)

What are the properties of your ProfileImage model?

  1. Set up the relevant relationships on your User and ProfileImage models. (see below)
  2. You then need to simply create a ProfileImage and assign it to the authenticated User (see below)

User (Model)

public function profileImage() {
    return $this->hasOne(ProfileImage::class);
}

ProfileImage (Model)

public function user() {
    return $this->belongsTo(User::class);
}

Controller

I've broken this down into steps. Some can be simplified.

$user = auth->user();

$user->profileImage()->create([
    'filename' => $filename
]);

This of course depends on what else you have defined in your ProfileImage model. Make sure that the field is $fillable too.

osherdo's avatar

@mstnorris thanks, will checkout and reply here to let you know what is up with it.

1 like

Please or to participate in this conversation.