Dropzone.js并在Laravel 5.1中显示请求验证错误

时间:2016-02-11 18:56:36

标签: jquery ajax validation laravel-5.1 dropzone.js

我正在使用dropzone.js上传文件。在我的控制器方法中,我有以下验证设置:

$this->validate($request, ['logo' => 'image|mimes:jpg,jpeg,gif']);

如果验证失败它会抛出422服务器响应,验证错误为json

{"logo":["The logo must be an image.","The logo must be a file of type: jpg, jpeg, gif."]}

使用dropzone.js,我如何解析错误并插入以下<p>标记:

@if ($errors->has('logo')) <p class="help-block" id="logo-error">{{ $errors->first('logo') }}</p> @endif

我在我的dropzone脚本中声明了一个错误事件,但是当我执行console.log时似乎没有任何内容:

var baseUrl = "{{ url('/') }}";
Dropzone.autoDiscover = false;

$("#my-dropzone").dropzone({
  url: baseUrl + "/upload",
  paramName: "logo",
  uploadMultiple: false,
  maxFiles: 1,
  dictDefaultMessage: '',
  init: function() {
    this.on("addedfile", function(file) {
      console.log('addedfile...');
      if (this.files[1]!=null){
        this.removeFile(this.files[0]);
      }
    });
    this.on("thumbnail", function(file, dataUrl) {
      console.log('thumbnail...');
      $('.dz-image-preview').hide();
      $('.dz-file-preview').hide();
    });
    this.on("sending", function(file, xhr, formData) {
      formData.append("_token", $('meta[name="csrf-token"]').attr('content'));
    });
    this.on("success", function(file, res) {
      console.log('upload success...');
      $('#img-thumb').attr('src', res.path);
      $('input[name="logo"]').val(res.path);
    });

  },
  error: function(file, response) {
    console.log(response);
  }
});

1 个答案:

答案 0 :(得分:0)

你需要在这里使用jQuery。由于您使用的是Laravel验证,因此将返回错误状态。这样我们就可以在你正在制作的AJAX请求的错误事件中编写所需的内容,即。 dropzone初始化在这里。示例代码如下所示,

success: function(file, response) {
        $('.profile-image-wrapper').removeClass('has-error');
        $('.profile-image-error').html('');
    },
    error: function(file, response) {
        var $message = response.errors.profilePhoto;
        $('.profile-image-wrapper').addClass('has-error');
        $('.profile-image-error').html('<strong>' +  $message + '</strong');
    },

&#34; paramName&#34;我的dropzone初始化的属性是&#34; profilePhoto&#34;。因此,错误也将以相同的顺序提供。