[英]Laravel4: upload a photo
我被卡住了......我想添加,以便通过表单添加新照片。 我正确设置了Photo资源。 表格照片包括:id,title,caption,path:string。
这是我在视图photo.create中直到现在所做的表格:
{{ Form::open(array('route' => 'photos.store'),'image/save', array('files'=> true)) }}
{{ Form::label('title', 'Title: ') }}
{{ Form::text('title') }}
{{ Form::label('caption', 'Caption: ') }}
{{ Form::textarea('caption') }} <br>
{{ Form::submit('Add Photo', array('class' => 'btn btn-primary' )) }}
{{ Form::close() }}
如何添加按钮,选择新文件?
谢谢!!
编辑:
这是我到目前为止所做的简单商店方法:
public function store()
{
$input = Input::all();
$rules = array('title' => 'required', 'path' => 'required');
$validation = Validator::make($input, $rules);
if ($validation->passes())
{
$photo = new Photo();
$photo->title = $input['title'];
$photo->caption = $input['caption'];
$photo->path = $input['path'];
$photo->save();
return Redirect::route('photos.index');
}
return Redirect::back()->withInput()->withErrors($validation)->with('message','There were validation message');
}
我怎样才能正确地在那里实现检索文件并存储在public / img中的文件夹中? 然后,我如何保存该路径并放入$ photo-> path?
非常感谢你!!
使用Form::file('image')
然后,您可以使用Input::file('image')
检索上传的文件,并使用Input::file('file')->move(YOUR_DESTINATION_PATH);
将其移动到目标Input::file('file')->move(YOUR_DESTINATION_PATH);
参考文献: http : //laravel.com/docs/requests#files和http://laravel.com/docs/html#file-input
编辑:
将上传的文件存储到public/img
: Input::file('file')->move(base_path() . '/public/img');
在数据库中存储路径:
$photo->path = base_path() . '/public/img' . Input::file('file')->getClientOriginalName(); // if you want your real path on harddrive
要么
$photo->path = URL::to('img/' . Input::file('file')->getClientOriginalName()); // if you want an exploitable path for http render
第二次编辑在表格http://paste.laravel.com/KX9上查看我的更正
@extends('master')
@section('blog')
<div class="span12 well">
{{ link_to_route('photos.index', 'Back to index') }}
</div>
<div class="span12 well">
{{ Form::open(array('route' => 'photos.store', 'files'=> true)) }}
{{ Form::label('title', 'Title: ') }}
{{ Form::text('title') }}
{{ Form::label('caption', 'Caption: ') }}
{{ Form::textarea('caption') }}
{{ Form::label('image', 'Image: ') }}
{{ Form::file('image') }}
<br>
{{ Form::submit('Add Photo', array('class' => 'btn btn-primary' )) }}
{{ Form::close() }}
<br><br>
@if($errors->any())
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
@endif
</div>
@stop
你可以使用Form::file('image');
{{ Form::open(array('action' => 'HomeController@upload', 'files'=>true)) }}
{{ Form::label('image', 'Upload Image')}}
{{ Form::file('image') }}
{{ Form::submit('Submit') }}
{{ Form::close() }}
第2步:
public function upload(){
$image = Input::file('image');
$savepath = 'public/uploads/';
$filename = $image->getClientOriginalName();
Input::file('image')->move($savepath, $filename);
}
最后一步:
Route::get('/upload' function()
{
return View::make('upload');
});
Route::post('/upload', 'HomeController@upload');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.