天天看点

laravel 文件上传下载

//文件上传表单
public function getFileupload()
{
    $postUrl = '/request/fileupload';
    $csrf_field = csrf_field();
    $html = <<<CREATE
<form action="$postUrl" method="POST" enctype="multipart/form-data">
$csrf_field
<input type="file" name="file"><br/><br/>
<input type="submit" value="提交"/>
</form>
CREATE;
    return $html;
}

//文件上传处理
public function postFileupload(Request $request){
    //判断请求中是否包含name=file的上传文件
    if(!$request->hasFile('file')){
        exit('上传文件为空!');
    }
    $file = $request->file('file');
    //判断文件上传过程中是否出错
    if(!$file->isValid()){
        exit('文件上传出错!');
    }
    $destPath = realpath(public_path('images'));
    if(!file_exists($destPath))
        mkdir($destPath,,true);
    $filename = $file->getClientOriginalName();
    if(!$file->move($destPath,$filename)){
        exit('保存文件失败!');
    }
    exit('文件上传成功!');
}
//下载 页面将会下载laravel-5-1.jpg文件并保存为Laravel学院.jpg
public function download(){
    return response()->download(
        realpath(base_path('public/images')).'/laravel-5-1.jpg',
        'Laravel学院.jpg'
    );
}