我有上传多个图像文件的表单,结合了Laravel 4.2和Ajax。但是当上传图像时,输入文件总是为NULL。我该如何解决?
这是我的上传表格。
{{ Form::open(array('url' => route('member.font.upload.images'), 'files'=>true, 'id'=>'upload-images', 'method'=> 'post')) }}
{{ Form::file('image[]', array('multiple'=>true, 'id'=>'images')) }}
<input type="hidden" name="font" value="{{ $font->id }}">
{{ Form::close() }}
在Controller中上传流程。
public function uploadImages()
{
$rules = array(
'font' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Response::json(['success' => false, 'message' => 'Failed upload image']);
} else {
if(Input::hasFile('image')){
$images = Input::file('image');
foreach($images as $image) {
$imagename = time() . $image->getClientOriginalName();
$upload = $image->move('images/', $imagename);
if($upload){
$data = new Image;
$data->font_id = Input::get('font');
$data->name = $imagename;
$data->save();
}
}
return Response::json(['success' => true, 'message' => 'Success']);
}else{
return Response::json(['success' => false, 'message' => 'File not found']);
}
}
}
然后是Ajax进程。
$('#images').change(function(e) {
e.preventDefault();
$.ajax({
url: $('#upload-images').attr('action'),
type: 'post',
dataType: 'json',
data: $('#upload-images').serialize(),
beforeSubmit: function() {
$('.add-images').removeClass('enabled').addClass('uploading');
},
success: function(data) {
$('.add-images').removeClass('uploading').addClass('enabled');
},
error: function() {}
});
});
答案 0 :(得分:1)
您可能需要定义表单的编码类型。
{{ Form::open(array('url' => route('member.font.upload.images'), 'files'=>true, 'id'=>'upload-images', 'method'=> 'post', 'enctype' => "multipart/form-data")) }}
您可以使用此W3Schools doc了解更多详情。
答案 1 :(得分:0)
更改此部分:
{{ Form::open(array('url' => route('member.font.upload.images'), 'files'=>true, 'id'=>'upload-images', 'method'=> 'post')) }}
要:
{{ Form::open(array('route' => 'member.font.upload.images', 'files'=>true, 'id'=>'upload-images', 'method'=> 'post')) }}