ThinkPHP5学习记录-上传文件

505 阅读2分钟

一、控制器定义

文件上传使用ThinkPHP5内置的think\File 类库,该类库可以轻松实现文件上传到本地服务器,如果需要上传到其它服务器或者平台,则需要后续调用其它类库或者接口。

二、创建项目

新建一个demo项目,部署到本地服务器上。

首先在index\controller创建一个Upload控制器如下:

<?php
namespace app\index\controller;
use think\Request;
class Upload extends Controller
{
    // 文件上传表单
    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());
        }
    }
}

ROOT_PATHthinkphp目录下的配置文件base.php

defined('ROOT_PATH') or define('ROOT_PATH', dirname(realpath(APP_PATH)) . DS);

$info定义文件存储的位置。

index目录下创建view\upload\index.html

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传示例</title>
<style>
body {
font-family:"Microsoft Yahei","Helvetica Neue",Helvetica,Arial,sans-serif;
font-size:16px;
padding:5px;
} 
.form{
padding: 15px;
font-size: 16px;
}
.form .text {
padding: 3px;
margin:2px 10px;
width: 240px;
height: 24px;
line-height: 28px;
border: 1px solid #D4D4D4;
}
.form .btn{
margin:6px;
padding: 6px;
width: 120px;
font-size: 16px;
border: 1px solid #D4D4D4;
cursor: pointer;
background:#eee;
} 
.form .file{
margin:6px;
padding: 6px;
width: 220px;
font-size: 16px;
border: 1px solid #D4D4D4;
cursor: pointer;
background:#eee;
}
a{
color: #868686;
cursor: pointer;
} 
a:hover{
text-decoration: underline;
} 
h2{
color: #4288ce;
font-weight: 400;
padding: 6px 0;
margin: 6px 0 0;
font-size: 28px;
border-bottom: 1px solid #eee;
} 
div{
margin:8px;
} 
.info{
padding: 12px 0;
border-bottom: 1px solid #eee;
}
</style>
</head>
<body>
<h2>文件上传示例</h2>
<FORM method="post" enctype="multipart/form-data" class="form" action="{:url('up')}">
选择文件:<INPUT type="file" class="file" name="file"><br/>
<INPUT type="submit" class="btn" value=" 提交 ">
</FORM>
</body>
</html>

再来更改一下虚拟主机,在Apache的httpd-vhosts.conf添加

#
<VirtualHost *:80>
	ServerName demo.com
	DocumentRoot "d:/wamp64/www/demo/public"
	<Directory  "d:/wamp64/www/demo/public/">
		Options +Indexes +Includes +FollowSymLinks +MultiViews
		AllowOverride All
		Require local
	</Directory>
</VirtualHost>

重启Apache,

三.上传

打开url demo.com/index/upload


可以看见文件上传成功


四、总结

在项目中可能会遇到需要文件上传,也会遇到很多没见过的问题,这时需要复杂问题拆分,从会的地方下手,一上来就往远端服务上传,如果实力允许那也是可以的,对于小白我还是从简单的入手,服务端的限制,官方文档上没有,需要自己实践。