【发布时间】:2016-05-22 17:22:39
【问题描述】:
我正在使用 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);
}
});
【问题讨论】:
-
对于任何寻求解决方案的人,请查看stackoverflow.com/a/66603779/5723524
标签: jquery ajax validation laravel-5.1 dropzone.js