您可以尝试我发布的此代码以帮助他人。
第一步是定义上传页面和上传处理Routes,像这样:
Route::get('image_', function() {
return View::make('image.upload-form');
});
Route::post('image_updade', 'ImageController@postUpload');
让您的image.upload-form 显示类似这样的内容(我使用的是简单的 HTML,而不是 Blade 模板):
<?php echo Form::open(array('url' => 'image_updade', 'files' => true, 'id' => 'myForm')) ?>
Name: <input type='file' name='image' id='myFile'/>
<br/>
Comment: <textarea name='comment'></textarea>
<br/>
<input type='submit' value='Submit Comment' />
<?php echo Form::close() ?>
现在您需要在该视图页面的 <HEAD> 标签中添加 JavaScript 文件:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js'></script>
<script src='http://malsup.github.com/jquery.form.js'></script>
<script>
// Wait for the DOM to be loaded
$(document).ready(function() {
// Bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert('Thank you for your comment!');
});
$('#myFile').change(function() {
$('#myForm').submit();
});
});
</script>
最后,这是一个简单的代码示例,用于ImageController@postUpload 控制器获取上传的文件,并将其移动到目标文件夹:
<?php
class ImageController extends BaseController {
public function getUploadForm() {
return View::make('image/upload-form');
}
public function postUpload() {
$file = Input::file('image');
$input = array('image' => $file);
$rules = array( 'image' => 'image');
$validator = Validator::make($input, $rules);
if ( $validator->fails() ){
return Response::json(['success' => false, 'errors' => $validator->getMessageBag()->toArray()]);
}
else {
$destinationPath = 'files/';
$filename = $file->getClientOriginalName();
Input::file('image')->move($destinationPath, $filename);
return Response::json(['success' => true, 'file' => asset($destinationPath.$filename)]);
}
}
}