0
点赞
收藏
分享

微信扫一扫

yii2多文件上传接口开发(特色,拥有时间目录,数据能保存到数据库中,postman测试,)

小月亮06 2022-05-14 阅读 34


如果你想到调通接口,请看我的文章。看完我的调通接口文章后,请在api/web/下新建一个uploads目录

yii2多文件上传接口开发(特色,拥有时间目录,数据能保存到数据库中,postman测试,)_php

postman:

yii2多文件上传接口开发(特色,拥有时间目录,数据能保存到数据库中,postman测试,)_php_02

yii2多文件上传接口开发(特色,拥有时间目录,数据能保存到数据库中,postman测试,)_上传_03

gii:生成model:一次能上传10个文件

<?php

namespace common\models;

use Yii;

/**
* This is the model class for table "upmore".
*
* @property integer $id
* @property string $name
* @property string $path
* @property string $time
*/
class Upmore extends \yii\db\ActiveRecord
{public $file;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'upmore';
}

/**
* @inheritdoc
*/
public function rules()
{
return [
[['file'], 'file', 'maxFiles' => 10,'extensions'=>'jpg,png,gif,txt,doc'],
];
}

/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'path' => 'Path',
'time' => 'Time',
];
}
}
:
<?php
namespace api\controllers;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use common\models\Upmore;
use yii\web\UploadedFile;
use Yii;
class UpmoreController extends \yii\rest\Controller{
public $enableCsrfValidation = false;
public function actionCreate(){
$model=new Upmore();
if (Yii::$app->request->isPost) {
$file = UploadedFile::getInstances($model, 'file');
$path='uploads/'.date("YmdH",time()).'/';
if ($file && $model->validate()) {
if(!file_exists($path)){
mkdir($path,0775,true);
}
foreach ($file as $fl) {
$fl->saveAs($path . $fl->baseName. '.' . $fl->extension);
Yii::$app->db->createCommand()->insert('upmore', [
'path'=>"/".$path.$fl->baseName. '.' . $fl->extension,
'name' =>$fl->baseName. '.' . $fl->extension,
'time'=>date('Y-m-d H:i:s')
])->execute();
}


}
}



}
}

yii2多文件上传接口开发(特色,拥有时间目录,数据能保存到数据库中,postman测试,)_上传_04



举报

相关推荐

0 条评论