共计 2628 个字符,预计需要花费 7 分钟才能阅读完成。
因为 TP6 很多功能比较新,还没有系统的学习,所以一直用的是 TP5。
最近在做一个后台管理程序,其中一个功能就是 excel 上传并导入数据,看文档抄代码的时候,发现官方文档给的代码会报错。
文档地址:https://www.kancloud.cn/manual/thinkphp5/155159
表单部分代码:
Haskell
1
2
3
4
|
<form action=“/index/index/upload” enctype=“multipart/form-data” method=“post”>
<input type=“file” name=“image” /> <br>
<input type=“submit” value=“ 上传 ” />
</form>
|
控制器部分代码:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public function upload(){
// 获取表单上传文件 例如上传了 001.jpg
$file = request()->file(‘image’);
// 移动到框架应用根目录 /public/uploads/ 目录下
if($file){
$info = $file->move(ROOT_PATH . ‘public’ . DS . ‘uploads’);
if($info){
// 成功上传后 获取上传信息
// 输出 jpg
echo $info->getExtension();
// 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
echo $info->getSaveName();
// 输出 42a79759f284b767dfcb2a0197904287.jpg
echo $info->getFilename();
}else{
// 上传失败获取错误信息
echo $file->getError();
}
}
}
|
这其中会报错,只需要修改成如下代码即可:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<?php
namespace appindexcontroller;
use thinkRequest;
class Upload extends thinkController
{
// 文件上传表单
public function index()
{
return $this->fetch();
}
// 文件上传提交
public function up(Request $request)
{
// 获取表单上传文件
$file = $request->file(‘file’);
if (empty($file)) {
$this->error(‘ 请选择上传文件 ’);
}
// 移动到框架应用根目录 /public/uploads/ 目录下
$info = $file->move(ROOT_PATH . ‘public’ . DS . ‘uploads’);
if ($info) {
$this->success(‘ 文件上传成功:’ . $info->getRealPath());
} else {
// 上传失败获取错误信息
$this->error($file->getError());
}
}
}
|
正文完