thinkphp實現圖片上傳功能分享_php執行個體

來源:互聯網
上載者:User

1.我們首先需要建立一個表

複製代碼 代碼如下:

CREATE TABLE IF NOT EXISTS `tp_image` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(200) NOT NULL,
  `create_time` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

2.然後再conf檔案裡添加配置(最後一段配置是可選的,只是為了方便統一管理URL路徑)

複製代碼 代碼如下:

<?php
return array(
        'URL_MODEL'    =>    2, // 如果你的環境不支援PATHINFO 請設定為3
        'DB_TYPE'    =>    'mysql',
        'DB_HOST'    =>    'localhost',
        'DB_NAME'    =>    'thinkphp',
        'DB_USER'    =>    'root',
        'DB_PWD'    =>    '',
        'DB_PORT'    =>    '3306',
        'DB_PREFIX'    =>    'tp_',

        'SHOW_PAGE_TRACE' =>true,        //顯示頁面調試明細

        'TMPL_PARSE_STRING' =>  array( // 地址替換,用_UPLOAD_目錄 代替 根目錄下的Upload目錄
         '__UPLOAD__'    =>  __ROOT__.'/Uploads',
     ),
);
?>

3.添加一個Image模組(名字可以隨便取)

複製代碼 代碼如下:

<?php
    class ImageAction extends Action{       

        /**
         * 建立index 入口方法
         */
        public function index(){
            $image=M('Image');                      
            $data=$image->order('create_time desc')->find();    //擷取最後上傳圖片
            $this->assign('data',$data);
            $this->display();
        }
?>

4.建立相應index視圖檔案(index.html)

複製代碼 代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #img{height:22px; border:#000 2px solid}
    #button{height:30px; width:100px;}
</style>
</head>
<body>
    <div class="result" >上傳允許檔案類型:gif png jpg 影像檔,並產生2張縮圖,其中大圖帶浮水印,產生後會刪除原圖。</div><br>
    <notempty name="data"><img src="__UPLOAD__/m_{$data.image}" /> <img src="__UPLOAD__/s_{$data.image}" /></notempty>
    <form action="__URL__/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="image" id="img"/>
        <input type="submit" value="上傳" id="button">
    </form>
</body>
</html>

5.選擇圖片,點擊上傳按鈕後,會跳到Image模組的upload方法上,Image模組上現在還沒有這個方法,於是我們建立它

複製代碼 代碼如下:

<?php
    class ImageAction extends Action{       

        /**
         * 建立index 入口方法
         */
        public function index(){
            $image=M('Image');                       
            $data=$image->order('create_time desc')->find();    //擷取最後上傳圖片

            var_dump($data);
            $this->assign('data',$data);
            $this->display();
        }

        //如果上傳的檔案不為空白,跳轉到_upload方法
        public function upload(){       
            //如果不為空白
            if(!empty($_FILES))
            {
                $this->_upload();
            }

        }

6.如果提交的不是NULL,則跳到_upload方法上,此方法實現圖片上傳的功能

複製代碼 代碼如下:

<?php
    class ImageAction extends Action{       

        /**
         * 建立index 入口方法
         */
        public function index(){
            $image=M('Image');                       
            $data=$image->order('create_time desc')->find();    //擷取最後上傳圖片

            var_dump($data);
            $this->assign('data',$data);
            $this->display();
        }

       
        //如果上傳的檔案不為空白,跳轉到_upload方法
        public function upload(){       
            //如果不為空白
            if(!empty($_FILES))
            {
                $this->_upload();
            }

        }

       
        /***
         * 實現圖片上傳
         */
        public function _upload(){
            import('@.ORG.UploadFile');
            //匯入上傳類
            $upload = new UploadFile();
            //設定上傳檔案大小
            $upload->maxSize            = 3292200;
            //設定上傳檔案類型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //設定附件上傳目錄
            $upload->savePath           = './Uploads/';
            //設定需要產生縮圖,僅對影像檔有效
            $upload->thumb              = true;
            // 設定引用圖片類庫包路徑
            $upload->imageClassPath     = '@.ORG.Image';
            //設定需要產生縮圖的檔案尾碼
            $upload->thumbPrefix        = 'm_,s_';  //生產2張縮圖
            //設定縮圖最大寬度
            $upload->thumbMaxWidth      = '400,100';
            //設定縮圖最大高度
            $upload->thumbMaxHeight     = '400,100';
            //設定上傳檔案規則
            $upload->saveRule           = 'uniqid';
            //刪除原圖
            $upload->thumbRemoveOrigin  = true;

           
            //如果上傳不成功
            if (!$upload->upload())
            {
                //捕獲上傳異常
                $this->error($upload->getErrorMsg());
            }
            else
            {
                //取得成功上傳的檔案資訊
                $uploadList = $upload->getUploadFileInfo();

               
                //匯入圖片類
                import('@.ORG.Image');               

                //給m_縮圖添加浮水印, Image::water('原檔案路徑','浮水印圖片地址')
                Image::water($uploadList[0]['savepath'] . 'm_' . $uploadList[0]['savename'], APP_PATH.'Tpl/Public/Images/logo.png');

                //圖片名賦值給 欄位image
                $_POST['image'] = $uploadList[0]['savename'];
            }
            $model  = M('image');
            //儲存當前資料對象
            $data['image']          = $_POST['image'];
            $data['create_time']    = NOW_TIME;
            $list   = $model->add($data);
            if ($list !== false)
            {
                $this->success('上傳圖片成功!');
            }
            else
            {
                $this->error('上傳圖片失敗!');
            }
        }       
    }
?>

上傳成功產生兩張縮圖

需要說明的是:

ThinkPHP裡內建的圖片上傳類(UploadFile.class.php) 和圖片模型類(Image.class.php),要完整版的ThinkPHP包才有。

沒有的話需要在Lib裡建立一個檔案夾(ORG),然後去官網下載擴充包把這兩個檔案放到ORG檔案夾中。

我的是第二種情況

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.