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


09-05 16:28