Files
2021-04-18 18:51:51 +08:00

89 lines
3.3 KiB
PHP

<?php
namespace Model;
use Think\Model;
class FileModel extends Model {
public function upload($files, $setting, $driver= 'Local', $config= null,$thumb=false) {
/* 上传文件 */
$setting['callback']= array($this, 'isFile');
$setting['removeTrash']= array($this, 'removeTrash');
$Upload= new \Think\Upload($setting, $driver, $config);
$info= $Upload->upload($files);
/* 设置文件保存位置 */
$this->_auto[]= array('location', 'ftp' === strtolower($driver) ? 1 : 0, self::MODEL_INSERT);
if ($info) { //文件上传成功,记录文件信息
foreach ($info as $key => &$value) {
//关联信息的随机id
$value['pubid']= I("get.pubid") ? I("get.pubid") : I("post.pubid");
$value['create_time']= time();
$value['filepath']= $setting['rootPath'] . $value['savepath'] . $value['savename'];
$value['filepath']= trim($value['filepath'], ".");
//是否自动生成小图
if($thumb){
//压缩图片
$image=new \Think\Image();
$image->open($setting['rootPath'] . $value['savepath'] . $value['savename']);
$image->thumb(200,200);
$small_path=$setting['rootPath'] . $value['savepath'] ."small_". $value['savename'];
$image->save($small_path);
$value['smallpath']=trim($small_path,".");
}
//
//赋值给info数组,返回给控制器
$info['smallpath']= $value['smallpath'];
$info['filepath']= $value['filepath'];
//
/* 已经存在文件记录 */
if (isset($value['id']) && is_numeric($value['id'])) {
//更新create_time
$this->save(array("id" => $value['id'], "create_time" => time(), "pubid" => $value['pubid']));
continue;
} else {
/* 不存在记录文件信息 */
if ($this->create($value) && ($id= $this->add())) {
$value['id'] = $id;
} else {
//TODO: 文件上传成功,但是记录文件信息失败,需记录日志
unset($info[$key]);
}
}
}
$info['id']= $value['id'];
return $info; //文件上传成功
} else {
$this->error= $Upload->getError();
return false;
}
}
/**
* 检测当前上传的文件是否已经存在
* @param array $file 文件上传数组
* @return boolean 文件信息, false - 不存在该文件
*/
public function isFile($file) {
if (empty($file['md5'])) {
throw new \Exception('缺少参数:md5');
}
/* 查找文件 */
$map= array('md5' => $file['md5'], 'sha1' => $file['sha1'],'name' => $file['name'],);
return $this->field(true)->where($map)->find();
}
/**
* 清除数据库存在但本地不存在的数据
* @param $data
*/
public function removeTrash($data) {
$this->where(array('id' => $data['id'],))->delete();
}
}