我正在使用 Dropzone js 处理多个文件上传。但是,文件不会传递给控制器。通过添加 CSRF 令牌的标头代码解决 419 发布错误后,出现 422 无法处理的实体错误。
根据网络日志的响应,它似乎影响了我之前工作正常的其他字段的验证。
{"message":"The given data was invalid.","errors":{"item-name.0":["The item-
name.0 field is required."],"item-quantity.0":["Please Enter Item
Quantity."],"availableStartDate":["The available start date field is
required."],"availableEndDate":["The available end date field is
required."],"preferredTime":["The preferred time field is required."]}}
这是 Blade 文件顶部的 Javascript 代码。
<script type="text/javascript">
Dropzone.autoDiscover = false;
$(document).ready(function () {
new Dropzone('#fileInput', {
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 1000,
maxFiles: 100,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
url: '/make-a-donation',
addRemoveLinks:true,
headers: {
'X-CSRFToken': $('meta[name="token"]').attr('content')
},
init: function () {
var myDropzone = this;
var wrapperThis = this;
$("#submit-all").click(function (e) {
e.preventDefault();
myDropzone.processQueue();
});
//Removed sending and success functions respectively
}
});
});
</script>
以下是 HTML 代码:
<form class="form-horizontal myForm" method="POST" files="true" action="{{
route('postdonation') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="col-md-12">
<div id="fileInput" class="dropzone">
<div class="fallback">
<!--replaced files[] to file-->
<input name="file" type="file" multiple="multiple" id="fileUpload"/>
</div>
</div>
</div>
....
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" id="submit-all" class="btn btn-primary">
insert
</button>
</div>
</div>
...
</form>
在控制器处,
public function store(CreateDonationDetailsRequest $r) {
//Inserting other data in the form
.....
//Previously $r->file('files') as $file to
foreach ($r->file('file') as $file) {
$donationImages = new DonationImages();
// Set the destination path
$destination = '/donationImagesUpload/';
// Get the orginal filname or create the filename of your choice
$filename = $file->getClientOriginalName();
// Copy the file to the destination folder
$file->move(public_path($destination), $filename);
//Insert file name to database
$donationImages->donation_items_id = $donationItems->id;
$donationImages->photoName = $filename;
//Save images to database
$donationItems->donationImages()->save($donationImages);
}
..
}