1. 程式人生 > >使用thinkphp實現上傳檔案(uploadify外掛)

使用thinkphp實現上傳檔案(uploadify外掛)

語言:php

框架:thinkphp3.2.3

上傳外掛:uploadify

1、在html頁面或者模板中引入CSS和JS

<link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadfy/uploadify.css" />
<script type="text/javascript" src="/Public/uploadfy/jquery.uploadify.min.js"></script>

2、在html中放入上傳按鈕
<input id="upload_button" type="file" multiple="true" value="" />
3、使用JS初始化按鈕並繫結事件
$('#upload_button').uploadify({
        'swf'      : '/Public/uploadfy/uploadify.swf',
        'uploader' : '/Manage/Admin/uploadify',//這個就是處理上傳檔案的地址
        'buttonText' : '上傳照片',
        'onUploadSuccess' : function(file, data, response) {
            data.trim();//這個是檔案在伺服器上的路徑,如果是圖片,可以使用src
        }
    });

4、thinkphp的Manage模組下Admin控制器的uploadify

public function uploadify(){
        if (!empty($_FILES)) {
            import("@.Think.UploadFile");
            $upload = new \Think\Upload();
            $upload->rootPath  = 'upload/';//根路徑
            $upload->savePath = date('Y').'/'.date('m').'/'.date('d').'/';//子路徑,資料夾自動分級好點,不然檔案太多了數量大了以後不好找圖片
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg', 'bmp', 'doc', 'xls', 'mp4', 'avi', 'docx', 'xlsx');//可以上傳的檔案型別
            $upload->autoSub = false;
            $upload->saveRule = uniqid; //上傳規則,檔名會自動重新獲取,這樣保證檔案不會被覆蓋
            $info = $upload->upload();
            if(!$info){
                echo $this->error($upload->getError());//獲取失敗資訊
            } else {
                //成功
                $fileArray = "";
                foreach ($info as $file) {
					//返回檔案在伺服器上的路徑
                    $fileArray = '/'.$upload->rootPath . $file['savepath'] . $file['savename'];
                }
                echo trim($fileArray);
            }
        }
    }