将HTML文件输入转换为Dropzone

5

我想将Dropzone用作另一个表单的文件输入框。

以下是使用<input type="file">的代码,借助于Dropzone.jsStackoverflow提供的帮助:

<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>

我尝试过不同的方法来使用dropzone和div一起工作,例如:

<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>

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被显示在表单中,甚至可以加载(和删除)图片,但是当我提交表单时,服务器端没有收到任何关于图片的数据。使用普通的input type="file"时,数据会按照需要被接收……

我无法理解在div中使用单独的action=""和JS中的url:""的用法,因为我不需要单独的URL来处理文件。我想通过表单的action路由一起提交它。

顺便说一下,我正在使用PHP-Laravel来处理服务器端。


当您选择文件时,控制台中是否有任何JS错误? - nlyn
控制台没有任何错误。 - TalESid
我说过dropzone正在工作,但它没有将值提交为表单的文件输入!!! - TalESid
哈,好的 - 祝你好运。 - nlyn
2个回答

5

在使用Drupal时,我发现放弃Dropzone.js并通过JQuery实现本地拖放行为更容易,这是代码:

  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 
    }
  })

我用这个创建了自己的dropzone,只花了30分钟就能运行,而不是像之前折腾dropzone.js四个小时。这个简单、灵活,应该是很多人在多个线程上询问如何使用dropzone的问题的答案。100! - J_sdev
有没有办法使用这段代码添加漂亮的拖放区域界面,就像缩略图预览和删除链接选项一样? - Demian

1
你可以使用不同的方法来管理它。
  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.


如果你能自己想出来并完成编码,那会更好。我已经更新了我的答案,并添加了更多的代码。希望这能帮助你更好地解决问题。 - Jobayer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接