ThinkPHP-文件上传和保存示例
导读:前端页面代码:<form action="/index.php/Upload/upload" method="post" enctype="multipart/form-data"> <input type="fi...
前端页面代码:
form action="/index.php/Upload/upload" method="post" enctype="multipart/form-data">
input type="file" name="file">
input type="submit" value="上传">
/form>
后端控制器代码::
?php
namespace app\index\controller;
use think\Controller;
class Upload extends Controller
{
public function index()
{
return $this->
fetch();
}
public function upload()
{
$file = request()->
file('file');
$info = $file->
validate(['size'=>
2048000,'ext'=>
'jpg,png,gif'])->
move( './uploads');
if ($info) {
// 文件上传成功,返回文件路径
$path = './uploads/' . $info->
getSaveName();
$content = 'hello, world!';
file_put_contents($path, $content);
return '文件上传成功!';
}
else {
// 文件上传失败,返回错误信息
return $file->
getError();
}
}
}
在上述代码中,我们首先定义了一个 Upload 控制器,其中包括一个 index() 函数用于展示上传页面,和一个 upload() 函数用于处理文件上传和保存操作。在 upload() 函数中,我们使用 request() 函数获取文件对象 $file,然后使用 validate() 函数对文件进行验证,包括文件大小和扩展名的验证,最后使用 move() 函数将文件保存到指定目录下。如果文件上传成功,我们将文件保存到指定路径下,并返回“文件上传成功!”的提示信息;如果文件上传失败,则返回错误信息。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: ThinkPHP-文件上传和保存示例
本文地址: https://pptw.com/jishu/291371.html