From b461b5c51e805c6f64df1c396cc57e740060038e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=82=B9=E6=99=AF=E7=AB=8B?= <zoujingli@qq.com>
Date: Tue, 21 Feb 2017 18:42:41 +0800
Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=96=87=E4=BB=B6=E4=B8=8A?=
 =?UTF-8?q?=E4=BC=A0=E7=BB=84=E4=BB=B6?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 application/admin/controller/Plugs.php   | 82 ++++++++++++++++++++++--
 application/admin/view/plugs.upfile.html | 19 +++---
 extend/library/File.php                  | 18 ++++++
 3 files changed, 105 insertions(+), 14 deletions(-)

diff --git a/application/admin/controller/Plugs.php b/application/admin/controller/Plugs.php
index 02e359d63..dec36ad14 100644
--- a/application/admin/controller/Plugs.php
+++ b/application/admin/controller/Plugs.php
@@ -3,6 +3,7 @@
 namespace app\admin\controller;
 
 use controller\BasicAdmin;
+use library\File;
 
 /**
  * 插件助手控制器
@@ -29,14 +30,85 @@ class Plugs extends BasicAdmin {
      * 文件上传
      */
     public function upfile() {
-        $this->assign('field', $this->request->get('field', 'file'));
-        $this->assign('types', '');
-        $this->assign('mimes', '');
+        $types = $this->request->get('type', 'jpg,png');
+        $field = $this->request->get('field', 'file');
+        $this->assign('field', $field);
+        $this->assign('types', $types);
+        $this->assign('mimes', File::getMine($types));
         $this->assign('uptype', '');
         return view();
     }
-    
-    public function upload(){
+
+    /**
+     * 检查文件上传状态
+     */
+    public function upstate() {
+        $data = $this->request->post();
+
+        $this->result($data, 'IS_UPLOADED');
+        $this->result($data, 'NOT_FOUND');
+    }
+
+    /**
+     * 生成七牛文件上传Token
+     * @param string $key
+     * @return string
+     */
+    protected function _getToken($key) {
+        $accessKey = sysconf('qiniu_accesskey');
+        $secretKey = sysconf('qiniu_secretkey');
+        $bucket = sysconf('qiniu_bucket');
+        $host = sysconf('qiniu_domain');
+        $protocol = sysconf('qiniu_protocol');
+        $time = time() + 3600;
+        if (empty($key)) {
+            exit('param error');
+        } else {
+            $data = array(
+                "scope"      => "{$bucket}:{$key}",
+                "deadline"   => $time,
+                "returnBody" => "{\"data\":{\"site_url\":\"{$protocol}://{$host}/$(key)\",\"file_url\":\"$(key)\"}, \"code\": \"SUCCESS\"}",
+            );
+        }
+        $find = array('+', '/');
+        $replace = array('-', '_');
+        $data = str_replace($find, $replace, base64_encode(json_encode($data)));
+        $sign = hash_hmac('sha1', $data, $secretKey, true);
+        return $accessKey . ':' . str_replace($find, $replace, base64_encode($sign)) . ':' . $data;
+    }
+
+    /**
+     * 文件上传
+     * @return string
+     */
+    public function upload() {
+        if (request()->isPost()) {
+            $filepath = 'upload/' . date('Y/md');
+            $file = request()->file('file');
+            $info = $file->move($filepath);
+            if ($info) {
+                $data = [];
+                $data['uptype'] = 'local';
+                $data['md5'] = input('post.md5', $info->md5());
+                $data['file_name'] = $info->getFilename();
+//                $data['file_type'] = $info->getInfo('type');
+                $data['file_path'] = $info->getPathname();
+                $data['full_path'] = $info->getRealPath();
+                $data['orig_name'] = $info->getInfo('name');
+                $data['client_name'] = $info->getInfo('name');
+                $data['file_ext'] = $info->getExtension();
+                $data['file_url'] = $filepath . '/' . $info->getSaveName();
+                $data['site_url'] = pathinfo(request()->baseFile(true), PATHINFO_DIRNAME) . '/' . $data['file_url'];
+                $data['file_size'] = $info->getSize();
+                $data['create_by'] = get_user_id();
+                Db::table('system_file')->insert($data);
+                return json(['code' => 'SUCCESS', 'data' => $data]);
+            }
+        }
+        return json([]);
+    }
+
+    public function upload() {
         
     }
 
diff --git a/application/admin/view/plugs.upfile.html b/application/admin/view/plugs.upfile.html
index 6c53c740d..6585010ac 100644
--- a/application/admin/view/plugs.upfile.html
+++ b/application/admin/view/plugs.upfile.html
@@ -1,7 +1,7 @@
 <!DOCTYPE html>
 <html lang="zh-CN">
     <head>
-        <title><{'app_name'|sysconf}> <{'app_version'|sysconf}></title>
+        <title>{'app_name'|sysconf} {'app_version'|sysconf}</title>
         <meta charset="utf-8">
         <link rel="icon" href="../image/favicon.ico">
         <meta http-equiv="X-UA-Compatible" content="IE=edge">
@@ -39,7 +39,7 @@
              */
             function uploaded(ret, file) {
                 $('#' + file.id).attr('data-md5', file.md5).attr('data-src', ret.url || ret.site_url);
-                top.$('[name="<{$field}>"]').map(function () {
+                top.$('[name="{$field}"]').map(function () {
                     top.$(this).attr('data-srcs', ret.url).attr('data-md5', file.md5).val(ret.url || ret.site_url).trigger('change');
                 });
                 //top.$.msg.tips('文件上传成功!');
@@ -158,17 +158,18 @@
                             deferred.reject();
                         }).then(function (md5) {
                             file.md5 = md5;
-                            $.ajax("<{'plugs/file/upstate'|url}>", {
+                            $.ajax("{:url('admin/plugs/upstate')}", {
                                 dataType: 'json',
                                 method: 'post',
                                 data: {
                                     id: file.id,
                                     md5: md5,
-                                    uptype: '<{$uptype}>',
+                                    uptype: '{$uptype}',
                                     filename: file.name,
                                 },
                                 success: function (ret) {
-                                    if (ret.code === 'SUCCESS') {
+                                    if (ret.code !== 'IS_UPLOADED') {
+                                        // 文件
                                         owner.skipFile(file);
                                         uploaded.call(uploader, ret.data, file);
                                         console.log('文件秒传成功!file -> ' + file.name);
@@ -197,8 +198,8 @@
                     },
                     accept: {
                         title: '选择文件',
-                        extensions: '<{$types}>', //'gif,jpg,jpeg,bmp,png',
-                        mimeTypes: '<{$mimes}>'
+                        extensions: '{$types}', //'gif,jpg,jpeg,bmp,png',
+                        mimeTypes: '{$mimes}'
                     },
                     formData: {},
                     auto: true,
@@ -208,7 +209,7 @@
                     swf: '__STATIC__/plugs/uploader/Uploader.swf',
                     chunked: false,
                     chunkSize: 512 * 1024,
-                    server: '<{"plugs/file/upload"|url}>',
+                    server: '{"plugs/file/upload"|url}',
                     disableGlobalDnd: true,
                     fileNumLimit: 1,
                     fileSizeLimit: 200 * 1024 * 1024, // 200 M
@@ -295,7 +296,7 @@
                                 img = $('<img src="' + src + '">');
                                 $wrap.empty().append(img);
                             } else {
-                                $.ajax('<{"plugs/file/preview"|url}>', {
+                                $.ajax('{"plugs/file/preview"|url}', {
                                     method: 'POST',
                                     data: src,
                                     dataType: 'json'
diff --git a/extend/library/File.php b/extend/library/File.php
index 0945aebfc..43d89fd42 100644
--- a/extend/library/File.php
+++ b/extend/library/File.php
@@ -15,6 +15,24 @@ use think\Log;
  */
 class File {
 
+    /**
+     * 获取文件MINE信息
+     * @param string $exts
+     * @return string
+     */
+    static public function getMine($exts) {
+        $_exts = is_string($exts) ? explode(',', $exts) : $exts;
+        $_mines = [];
+        $mines = require(__DIR__ . DS . 'resource' . DS . 'mines.php');
+        foreach ($_exts as $_e) {
+            if (isset($mines[strtolower($_e)])) {
+                $_exinfo = $mines[strtolower($_e)];
+                $_mines[] = is_array($_exinfo) ? join(',', $_exinfo) : $_exinfo;
+            }
+        }
+        return join(',', $_mines);
+    }
+
     /**
      * 存储微信上传的文件
      * @param string $appid 公众号APPID