HTML File input to Dropzone
Asked Answered
S

2

5

I want to use dropzone as a file input of another form

Following is the code with <input type="file"> with some help from Dropzone.js and Stackoverflow:

<form class="form-horizontal" action="/details/store" method="post" enctype="multipart/form-data">
    {{ csrf_field() }}
    <div class="row">
        <div class="form-group col-lg-6">
            <label for="title" class="control-label col-lg-3 text-semibold">Title</label>
            <div class="col-lg-9 {{ $errors->has('title') ? 'has-error' : '' }}">
                <input name="title" type="text" class="form-control" value="{{ old('title') }}" required>

                @if ($errors->has('title'))
                  <span class="help-block">{{ $errors->first('title') }}</span>
                @endif
            </div>
        </div>

        <div class="form-group col-lg-6">
            <label for="subtitle" class="control-label col-lg-3 text-semibold">Sub Title</label>
            <div class="col-lg-9">
                <input name="subtitle" type="text" class="form-control" value="{{ old('subtitle') }}">
            </div>
        </div>

        <div class="form-group col-lg-12">
            <label for="description" class="control-label col-lg-1 text-semibold">Description</label>
            <div class="col-lg-11">
                <textarea name="description" class="form-control">{{ old('description') }}</textarea>
            </div>
        </div>

        <div class="form-group col-lg-12">
            <label for="images" class="control-label col-lg-1 text-semibold">Images</label>
            <div class="col-lg-9" style="margin-left:4em;">
                <span class="help-block text-semibold" style="color:blue">Accepted Formats: .jpg, .jpeg, .png, .gif</span>

<!-- Here is the file input I want to convert to dropzone -->
                <input type="file" name="images[]" class="file-styled btn btn-primary" accept=".jpg, .jpeg, .png" required multiple>

                <span class="help-block">Accepted formats: png, jpg, gif</span>
                @if ($errors->has('images'))
                  <span class="help-block">{{ $errors->first('images') }}</span>
                @endif
            </div>
        </div>
    </div>

    <div class="text-center">
        <button type="submit" class="btn btn-primary">Create</button>
    </div>
</form>

I have tried different methods to use dropzone with div like:

<div action="#" id="dropzone" class="dropzone">
    <div class="fallback">
        <input type="file" name="images[]" class="file-styled btn btn-primary" accept=".jpg, .jpeg, .png" required multiple>
    </div>
</div>

and JS

Dropzone.options.dropzone = {
  url: "/properties/store",
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  },
  autoProcessQueue:false,
  uploadMultiple:true,
  paramName:"images",
  maxFilesize:1,
  maxFiles:10,
  addRemoveLinks:true,
  acceptedFiles: ".jpeg,.jpg,.png,.gif",
};

Dropzone is being shown inside the form and it is even loading (and removing) images as well, but when I submit the form, nothing recieved on the server side as images. With normal input type="file" data was being recieved as needed...

I can't understand the use of separate action="" in div and url:"" in JS, as I don't need separate URL for files. I want to submit it along with the form using form's action route.

BTW, I am using PHP-Laravel for server side handling.

Stilton answered 6/5, 2018 at 1:21 Comment(4)
Any JS errors in your console when you select the file?Okeefe
nothing... no error in console.Stilton
I said dropzone is working but it is not submitting values as file input of the form !!!Stilton
Ha, okay - best of luck with that.Okeefe
L
5

Working with Drupal, I've found it easier to ditch Dropzone.js and implement native drag and drop behavior via JQuery, here is the code:

  const dropzone = $('#fieldWrapper')

  // click input file field
  dropzone.on('click', function () {
    $("#inputID").trigger("click");
  })

  // prevent default browser behavior
  dropzone.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {
      e.preventDefault();
      e.stopPropagation();
    })

  // add visual drag information  
  dropzone.on('dragover dragenter', function() {
      $('#fieldWrapper').addClass('active');
    })
  dropzone.on('dragleave dragend', function() {
    $('#fieldWrapper').removeClass('active');
    }) 

  // catch file drop and add it to input
  dropzone.on("drop", e => {
    e.preventDefault();
    let files = e.originalEvent.dataTransfer.files

    if (files.length) {
      $("#inputID").prop("files", files);
    }
  });

  // trigger file submission behavior
  $("#inputID").on('change', function (e) {
    if (e.target.files.length) {
      // trigger any behavior here 
    }
  })
Lowboy answered 22/3, 2020 at 13:29 Comment(2)
I used this to create my own dropzone and I was up and running in 30 minutes versus fighrting dropzone.js for the last 4 hours. This is simple, flexible and should be the answer to a lot of people's problems on mutliple threads asking about how to use dropzone other than its intended usage. 100!Diaphysis
Is there a way to add the nice dropzone interface like the thumbnail preview and removeLink options using this code?Vashti
S
1

you can manage it using a different approach.

  1. Remove this one autoProcessQueue:false, & use a separate url(instead of url: "/properties/store") for your image uploading. You can use something like below code

    Dropzone.options.dropzone = {
      url: "/your_controller/store_image",
      sending: function(data, xhr, formData){
          formData.append('_token', "{{ csrf_token() }}" );
    
       },
    
      paramName:"images",
    
      maxFiles:10,
      addRemoveLinks:true,
      acceptedFiles: ".jpeg,.jpg,.png,.gif",
      success: function(results, callback){
        //set value of your hidden input field here
        console.log(results['name']);
      }
    }; 
    
  2. Then using that url, manage those uploaded files inside a temporary folder & use a hidden field to store those files data inside your main form.

    public function store_image(Request $request){
      $file = Input::file('images');
      //getting image extension
      $extension = Input::file($filename)->getClientOriginalExtension(); 
      //renameing image
      $fileName = time() . '-' . uniqid() . '.' .$extension; 
      //uploading file to given path
        Input::file($filename)->move($destinationPath, $fileName); 
       echo json_encode($file->getClientOriginalName());
      }
    
  3. Finally you can save your form data without any hassle. When user submit main form, move your files to main folders & save your related data to db.

Schadenfreude answered 6/5, 2018 at 6:7 Comment(1)
it's will be better if you can figure out it by yourself & complete coding. I have updated my answer with more code. Hope it will help you more to fix itSchadenfreude

© 2022 - 2024 — McMap. All rights reserved.