Commit 95a834ada3a149f8636eea94beaeb29ce18254ac

Authored by zhang
1 parent ea6fd439

[留言板]留言信息中素材上传

trunk/Message/Common/Model/AttachmentModel.class.php 0 → 100644
  1 +<?php
  2 +namespace Common\Model;
  3 +
  4 +
  5 +/**
  6 + * 素材附件模型类
  7 + */
  8 +class AttachmentModel extends AbstractModel
  9 +{
  10 + const UPLOAD_IMAGE_SIZE = 20000000;
  11 +
  12 + private $upload_dir = '../../trunk/Message/attachment/';
  13 +
  14 + // 素材入库
  15 + public function add()
  16 + {
  17 + $bool = false;
  18 + $attachment = $this->initAttac();
  19 +
  20 +
  21 + if(is_array($attachment) && $attachment){
  22 + $bool = $this->_m->insert_all($attachment);
  23 + }
  24 + return boolval($bool);
  25 + }
  26 +
  27 + /**
  28 + * 整理素材入库数据
  29 + * @author <362431947@qq.com>
  30 + * @date 2018-10-09
  31 + * @return array
  32 + */
  33 + private function initAttac()
  34 + {
  35 + $attachment = [];
  36 + $index = 0;
  37 + foreach ($_FILES as $key => $file) {
  38 + $attachment[$index]['path'] = $this->upload($file);
  39 + $attachment[$index]['domain'] = md5($_SERVER['HTTP_HOST']);
  40 + $attachment[$index]['created'] = $this->microtime();
  41 +
  42 + $index++;
  43 + }
  44 + return $attachment;
  45 + }
  46 + /**
  47 + * 素材附件上传
  48 + * @author <362431947@qq.com>
  49 + * @date 2018-10-09
  50 + * @param array $file
  51 + * @param string $subdir
  52 + * @return mixed
  53 + */
  54 + public function upload(array $file,$subdir='')
  55 + {
  56 + if($file['error'])
  57 + {
  58 + E('文件上传失败!');
  59 + return false;
  60 + }
  61 +
  62 + $suffix = strrchr($file['name'],'.');
  63 + //获取文件后缀.从文件名最后一个点开始截取知道结束
  64 +
  65 + if(! in_array($suffix,['.jeg','.jpeg','.png']))
  66 + {
  67 + E('上传文件类型错误(后缀)!');
  68 + }
  69 +
  70 + if($file['size'] > self::UPLOAD_IMAGE_SIZE)
  71 + {
  72 + E('上传文件不能超过' . self::UPLOAD_IMAGE_SIZE/1000 . 'k');
  73 + }
  74 +
  75 + $subdir = $subdir . date('Y/m/');
  76 + if(! is_dir($this->upload_dir . $subdir))
  77 + {
  78 + $this->mkDirs($this->upload_dir . $subdir);
  79 + if(! $this->mkDirs($this->upload_dir . $subdir)){
  80 + E("子目录创建失败");
  81 + }
  82 + }
  83 +
  84 + $basename = uniqid('message',true) . $suffix;
  85 + //如果目录不存在,递归创建
  86 + if(move_uploaded_file($file['tmp_name'],$this->upload_dir . $subdir . $basename))
  87 + {
  88 + // echo $subdir . $basename;
  89 + return $subdir . $basename;
  90 + }
  91 + else{
  92 + E("文件移动失败");
  93 + }
  94 + }
  95 + /**
  96 + * 递归创建目录
  97 + * @author <362431947@qq.com>
  98 + * @date 2018-10-09
  99 + * @param string $dir
  100 + * @return bool
  101 + */
  102 + private function mkDirs($dir = '')
  103 + {
  104 + if(!is_dir($dir)){
  105 + if(! $this->mkDirs(dirname($dir))){
  106 + return false;
  107 + }
  108 + if(!mkdir($dir,0777)){
  109 + return false;
  110 + }
  111 + }
  112 + return true;
  113 + }
  114 +}
... ...