天天看點

fastadmin無法上傳視訊和檔案上傳到七牛的操作

在fastadmin的文檔中,資料庫群組件–》檔案上傳部分介紹了檔案和圖檔的上傳,但是實際操作之後發現字段字尾改成file,檔案大小限制修改之後,依然不能進行視訊上傳,始終報錯檔案格式受限制的問題,這裡記錄一下解決方法

1.首先找到你的html檔案,在生成的源代碼上添加2個屬性data-mimetype和data-maxsize,這2個屬性文檔中有介紹

<div class="form-group">
                <label class="control-label col-xs-12 col-sm-2">{:__('Vedio_file')}:</label>
                <div class="col-xs-12 col-sm-8">
                    <div class="input-group">
                        <input id="c-vediofile" class="form-control" size="50" name="row[vedio_file]" type="text">
                        <div class="input-group-addon no-border no-padding">
                            <span><button type="button" id="plupload-vediofile" class="btn btn-danger plupload"
                                          data-input-id="c-vediofile" data-mimetype="mp4,mp3,avi,flv,wmv"
                                          data-multiple="false" data-maxsize="1024M"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
                            <span><button type="button" id="fachoose-vediofile" class="btn btn-primary fachoose"
                                          data-input-id="c-vediofile" data-mimetype="mp4,mp3,avi,flv,wmv"
                                          data-multiple="false"><i
                                    class="fa fa-list"></i> {:__('Choose')}</button></span>
                        </div>
                        <span class="msg-box n-right" for="c-vediofile"></span>
                    </div>

                </div>
            </div>      

PHP

Copy

2.找到檔案上傳的php,在application/admin/controller/Ajax.php,修改裡面的upload方法,在此基礎上添加視訊上傳的代碼即可

/**
    * 上傳檔案
    */
   public function upload()
   {
       Config::set('default_return_type', 'json');
       $file = $this->request->file('file');
       if (empty($file)) {
           $this->error(__('No file upload or server upload limit exceeded'));
       }

       //判斷是否已經存在附件
       $sha1 = $file->hash();
       $extparam = $this->request->post();

       $upload = Config::get('upload');

       preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
       $type = strtolower($matches[2]);
       $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
       $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
       $fileInfo = $file->getInfo();
       $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
       $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';

       $mimetypeArr = explode(',', strtolower($upload['mimetype']));
       $typeArr = explode('/', $fileInfo['type']);

       //禁止上傳PHP和HTML檔案
       if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
           $this->error(__('Uploaded file format is limited'));
       }
       //驗證檔案字尾
       if ($upload['mimetype'] !== '*' &&
           (
               !in_array($suffix, $mimetypeArr)
               || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
           )
       ) {
           $this->error(__('Uploaded file format is limited'));
       }
       //驗證是否為圖檔檔案或視訊檔案
       $imagewidth = $imageheight = 0;
       if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp', 'swf', 'mp4', 'mp3', 'avi', ',flv', 'wmv'])) {
           $imgInfo = getimagesize($fileInfo['tmp_name']);
           if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
               $this->error(__('Uploaded file is not a valid image'));
           }
           $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
           $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
       }
       $replaceArr = [
           '{year}'     => date("Y"),
           '{mon}'      => date("m"),
           '{day}'      => date("d"),
           '{hour}'     => date("H"),
           '{min}'      => date("i"),
           '{sec}'      => date("s"),
           '{random}'   => Random::alnum(16),
           '{random32}' => Random::alnum(32),
           '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
           '{suffix}'   => $suffix,
           '{.suffix}'  => $suffix ? '.' . $suffix : '',
           '{filemd5}'  => md5_file($fileInfo['tmp_name']),
       ];
       $savekey = $upload['savekey'];
       $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

       $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
       $fileName = substr($savekey, strripos($savekey, '/') + 1);
       //
       $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
       if ($splInfo) {
           $params = array(
               'admin_id'    => (int)$this->auth->id,
               'user_id'     => 0,
               'filesize'    => $fileInfo['size'],
               'imagewidth'  => $imagewidth,
               'imageheight' => $imageheight,
               'imagetype'   => $suffix,
               'imageframes' => 0,
               'mimetype'    => $fileInfo['type'],
               'url'         => $uploadDir . $splInfo->getSaveName(),
               'uploadtime'  => time(),
               'storage'     => 'local',
               'sha1'        => $sha1,
               'extparam'    => json_encode($extparam),
           );
           $attachment = model("attachment");
           $attachment->data(array_filter($params));
           $attachment->save();
           \think\Hook::listen("upload_after", $attachment);
           $this->success(__('Upload successful'), null, [
               'url' => $uploadDir . $splInfo->getSaveName()
           ]);
       } else {
           // 上傳失敗擷取錯誤資訊
           $this->error($file->getError());
       }
   }      

PHP

Copy

3.這些修改好之後,如果出現上傳檔案或者圖檔上傳4-5個之後就會報錯,可以檢視自己的資料庫,在建立資料庫字段的時候,檔案和圖檔的字段類型是varchar,fastadmin才能生成對應的上傳檔案和圖檔,但是多圖和多檔案上傳的時候,你會發現這字段類型完全不夠用,這時需要我們手動修改對應字段類型為text,不需要重新生成一遍背景,問題解決。(建議手動添加 重新生成會清理前面寫好的邏輯代碼 )

下面是到七牛的修改 安裝配置好七牛的插件(要付錢自己內建也行哈) 作者用的是fastadmin七牛插件(比較懶而且有錢)

首先是admin/controller/ajax.php第94行 添加自己允許上傳的視訊格式(mp4', 'mp3', 'avi', ',flv', 'wmv')

視訊插件裡面addons/qinqiu/controller/index.php第83 同樣添加自己允許上傳的視訊格式(mp4', 'mp3', 'avi', ',flv', 'wmv')

​​

fastadmin無法上傳視訊和檔案上傳到七牛的操作

​​