UploadedFile 类有一个 store 方法,该方法会将上传文件移动到相应的磁盘路径上,该路径可以是本地文件系统的某个位置,也可以是云存储(如Amazon S3)上的路径。
store 方法接收一个文件保存的相对路径(相对于文件系统配置的根目录 ),该路径不需要包含文件名,因为系统会自动生成一个唯一ID作为文件名。
文件系统配置在config/filesystems.php中配置。
默认使用 local 配置存放上传文件,即本地文件系统,默认根目录是 storage/app,public 也是本地文件系统,只不过存放在这里的文件可以被公开访问,其对应的根目录是 storage/app/public,要让 Web 用户访问到该目录下存放文件的前提是在应用入口 public 目录下建一个软链 storage 链接到 storage/app/public
创建软链接
php artisan storage:link
文件被存储并且软链已经被创建的情况下,就可以使用辅助函数 asset 创建一个指向该文件的URL
{{ asset('storage/'.$val['image']) }}
form
<div class="form-group">
<label for="image" class="col-sm-1 control-label">{{ trans('backend.image') }}</label>
<div class="col-sm-11">
<input type="file" name="image" />
<input type="hidden" name="old_image" value="{{ $image }}" />
@if ($image != '')
<img src="{{ asset('storage/'.$image) }}" width="500" />
@endif
</div>
</div>
controller:
public function store(AdRequest $request)
{
$ad = Ad::create($request->fillData());
return redirect('backend/ad');
}
request:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AdRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required'
];
}
/**
* Return the fields and values to create a new post from
*/
public function fillData()
{
$path = $this->upload();
return [
'title' => $this->title,
'description' => $this->description,
'image' => $path
];
}
private function upload() {
if($this->image != '') {
if($this->old_image != '') {
@unlink('storage/' . $this->old_image);
}
$path = $this->image->store(config('web.uploads'), 'public');
} else {
$path = $this->old_image;
}
return $path;
}
}