1
https://www.kancloud.cn/manual/thinkphp5/155159
2
經常使用ThinkPHP3后,在使用ThinkPHP5上費了好些功夫,今天總結一下關於tp5的文件上傳,具體代碼詳情如下:
模板頁(一定要加上enctype="multipart/form-data"):
<form action="{:url('index/index/upQuestionsWrite')}" method="post" class="form form-horizontal" enctype="multipart/form-data" id="addform">
<div class="row cl">
<label class="form-label col-xs-4 col-sm-2">選擇試題文件:</label>
<div class="btn-upload form-group">
<input type="text" name="uploadfile" id="uploadfile" class="input-text upload-url radius" readonly><a href="javascript:void();" class="btn btn-primary radius"><i class="Hui-iconfont"></i>瀏覽文件</a>
<input type="file" name="examfile" class="input-file" multiple>
</div>
<boutton type="submit" class="btn btn-success btn-submit">導入試題</button>
</div>
</form>
控制器(在tp5中獲取上傳文件的文件名稱與tp3略有不同):
public function upQuestionsWrite()
{
// 獲取表單上傳文件
$file = request()->file('examfile');
if(empty($file)) {
$this->error('請選擇上傳文件');
}
// 移動到框架應用根目錄/public/uploads/ 目錄下
$info = $file->move(ROOT_PATH.'public'.DS.'upload');
//如果不清楚文件上傳的具體鍵名,可以直接打印$info來查看
//獲取文件(文件名),$info->getFilename() ***********不同之處,筆記筆記哦
//獲取文件(日期/文件名),$info->getSaveName() **********不同之處,筆記筆記哦
$filename = $info->getSaveName(); //在測試的時候也可以直接打印文件名稱來查看
if($filename){
$this->success('文件上傳成功!');
}else{
// 上傳失敗獲取錯誤信息
$this->error($file->getError());
}
}
// 上傳失敗獲取錯誤信息
$this->error($file->getError());
}
}
