欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

ThinkPHP上传图片是否存否数据库类

程序员文章站 2022-04-03 21:18:59
...
看下项目要求:可以选择是否存入数据库,指定文件类型,文件大小,缩略图及缩略图大小
  1. class AttachModel extends Model{
  2. /**
  3. * 附件上传
  4. * @param string $type 文件类型:jpg,png
  5. * @param int $maxsize 最大上传容量:默认100Kb
  6. * @param string $model 上传所在模块
  7. * @param bool $insert 是否写入数据库
  8. * @param bool $thumb 是否生成缩略图
  9. * @param string $wh 缩略图的宽高
  10. * Example: $upload->upload(null,102400,APP_NAME,true,true,array('300','225'));
  11. */
  12. public function upload($type = null, $maxsize = '102400', $model = null, $insert = true, $thumb = false, $wh = array('160', '120')){
  13. //导入上传类
  14. import('ORG.NET.UploadFile');
  15. $upload = new UploadFile();
  16. $upload->maxSize = $maxsize;
  17. if ($type){
  18. $type = explode(',', $type);
  19. $upload->allowExts = $type;
  20. }else{
  21. $upload->allowExts = array('jpg','png','gif','jpeg');
  22. }
  23. if ($model){
  24. $upload->savePath = '../Public/Uploads/'.$model.'/';
  25. }else{
  26. $upload->savePath = '../Public/Uploads/';
  27. }
  28. if ($thumb){
  29. $upload->thumb = true;
  30. $upload->thumbPrefix = 'zj_';
  31. $upload->thumbMaxWidth = $wh[0];
  32. $upload->thumbMaxHeight = $wh[1];
  33. }
  34. $upload->saveRule = uniqid;//上传图片命名规则
  35. if (!$upload->upload()) {
  36. return $upload->getErrorMsg();
  37. }else{
  38. $uploadlist = $upload->getUploadFileInfo();
  39. }
  40. if ($insert){
  41. return $this->_insert($uploadlist);
  42. }else{
  43. return $uploadlist;
  44. }
  45. }
  46. /*
  47. * 上传的附件整合成attach所需数据,存入表并返回数组
  48. * */
  49. private function _insert($uploadlist){
  50. $j = count($uploadlist);
  51. $v = array();
  52. foreach ($uploadlist as $key => $value)
  53. {
  54. $v[$key]['name'] = $value['name'];
  55. $v[$key]['hashname'] = $value['savename'];
  56. $v[$key]['savepath'] = substr($value['savepath'], 2);
  57. $v[$key]['bsize'] = $value['size'];
  58. $v[$key]['user_id'] = $_SESSION[C('USER_AUTH_KEY')];
  59. $v[$key]['create_time'] = time();
  60. $v[$key]['model_name'] = APP_NAME;
  61. $this->add($v[$key]);
  62. if($this->thumb)
  63. {
  64. $v[$key]['prefix'] = $this->thumbPrefix;
  65. }
  66. $v[$key]['id'] = M('Attach')->getLastInsID();
  67. }
  68. return $v;
  69. }
  70. }
复制代码
  1. DROP TABLE IF EXISTS `zj_attach`;
  2. CREATE TABLE `zj_attach` (
  3. `id` int(10) NOT NULL auto_increment,
  4. `name` varchar(100) NOT NULL COMMENT '附件名称',
  5. `hashname` varchar(100) default NULL,
  6. `status` tinyint(1) default '1' COMMENT '附件状态{1:启用,0:禁用}',
  7. `savepath` varchar(100) default NULL COMMENT '存储地址',
  8. `bsize` varchar(100) default NULL COMMENT '附件大小',
  9. `model_name` varchar(50) default NULL COMMENT '所属模块',
  10. `user_id` int(10) default NULL COMMENT '上传用户id',
  11. `create_time` int(10) default NULL COMMENT '上传时间',
  12. PRIMARY KEY (`id`)
  13. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
复制代码