文件上传
form表单\resources\views\form.blade.php
<form action = "{{route('posts.store')}}" method ="post" enctype ="multipart/form-data" >
{{ csrf_field() }}
<table>
<tr>
<td>photo</td>
<td><input type = "file" name = "photo" /></td>
</tr>
<tr>
<td><input type = "submit" value = "submin"/></td>
</tr>
</table>
</form>
提交到控制器:PostController@store
public function store(Request $request) {
//判断hasfile()上传文件是否存在并且isValid()文件是否上传出错:注意这里的photo指的是form表单里的name属性
if($request->hasfile('photo') && $request->file('photo')->isValid()){
//获取请求中的photo
$photo = $request->file('photo');
//extension()基于文件内容判断文件扩展名
$extension = $photo->extension();
//上传到\storage\app\photo
$store_result = $photo -> store('photo');
//上传到\storage\app\photo并且重命名为test.jpg
//$store_result = $photo->storeAs('photo', 'test.jpg');
$output = [
'extension' => $extension,
'store_result' => $store_result
];
echo "上传成功~</br>";
//打印出文件扩展名和上传路径
print_r($output);
exit();
}else{
echo "上传出错";
}
}
注意在上传文件前,得先修改php.ini
;extension=fileinfo => extension=fileinfo
浏览器访问:http://localhost:8000/form
选择一个文件然后提交
可在\storage\app\photo中看到上传的文件
文件下载
download方法用于生成强制用户浏览器下载给定路径文件的响应
storage_path用于获取路径
路由如下web.php:
Route::get('download/response', function() {
return response()->download(storage_path('app/photo/test.jpg'), '测试图片.jpg');
});
浏览器访问:http://localhost:8000/download/response
即可完成下载