dever 5 years ago
parent
commit
2a555004ba
5 changed files with 457 additions and 69 deletions
  1. 226 0
      lib/dever/components/qiniu/upload.js
  2. 1 1
      lib/dever/config.js
  3. 95 68
      lib/dever/index.js
  4. 127 0
      pages/dream/test.vue
  5. 8 0
      pages/dream/view/cate.vue

+ 226 - 0
lib/dever/components/qiniu/upload.js

@@ -0,0 +1,226 @@
+(function () {
+    // 请参考demo的index.js中的initQiniu()方法,若在使用处对options进行了赋值,则此处config不需要赋默认值。init(options) 即updateConfigWithOptions(options),会对config进行赋值
+    var config = {
+        // bucket 所在区域。ECN, SCN, NCN, NA, ASG,分别对应七牛云的:华东,华南,华北,北美,新加坡 5 个区域
+        qiniuRegion: '',
+        // 七牛云bucket 外链前缀,外链在下载资源时用到
+        qiniuBucketURLPrefix: '',
+
+        // 获取uptoken方法三选一即可,执行优先级为:uptoken > uptokenURL > uptokenFunc。三选一,剩下两个置空。推荐使用uptokenURL,详情请见 README.md
+        // 由其他程序生成七牛云uptoken,然后直接写入uptoken
+        qiniuUploadToken: '',
+        // 从指定 url 通过 HTTP GET 获取 uptoken,返回的格式必须是 json 且包含 uptoken 字段,例如: {"uptoken": "0MLvWPnyy..."}
+        qiniuUploadTokenURL: '',
+        // uptokenFunc 这个属性的值可以是一个用来生成uptoken的函数,详情请见 README.md
+        qiniuUploadTokenFunction: function () { },
+
+        // qiniuShouldUseQiniuFileName 如果是 true,则文件的 key 由 qiniu 服务器分配(全局去重)。如果是 false,则文件的 key 使用微信自动生成的 filename。出于初代sdk用户升级后兼容问题的考虑,默认是 false。
+        // 微信自动生成的 filename较长,导致fileURL较长。推荐使用{qiniuShouldUseQiniuFileName: true} + "通过fileURL下载文件时,自定义下载名" 的组合方式。
+        // 自定义上传key 需要两个条件:1. 此处shouldUseQiniuFileName值为false。 2. 通过修改qiniuUploader.upload方法传入的options参数,可以进行自定义key。(请不要直接在sdk中修改options参数,修改方法请见demo的index.js)
+        // 通过fileURL下载文件时,自定义下载名,请参考:七牛云“对象存储 > 产品手册 > 下载资源 > 下载设置 > 自定义资源下载名”(https://developer.qiniu.com/kodo/manual/1659/download-setting)。本sdk在README.md的"常见问题"板块中,有"通过fileURL下载文件时,自定义下载名"使用样例。
+        qiniuShouldUseQiniuFileName: false
+    }
+
+    // init(options) 将七牛云相关配置初始化进本sdk
+    // 在整个程序生命周期中,只需要 init(options); 一次即可
+    // 如果需要变更七牛云配置,再次调用 init(options); 即可
+    function init(options) {
+        updateConfigWithOptions(options);
+    }
+
+    // 更新七牛云配置
+    function updateConfigWithOptions(options) {
+        if (options.region) {
+            config.qiniuRegion = options.region;
+        } else {
+            console.error('qiniu uploader need your bucket region');
+        }
+        if (options.uptoken) {
+            config.qiniuUploadToken = options.uptoken;
+        } else if (options.uptokenURL) {
+            config.qiniuUploadTokenURL = options.uptokenURL;
+        } else if (options.uptokenFunc) {
+            config.qiniuUploadTokenFunction = options.uptokenFunc;
+        }
+        if (options.domain) {
+            config.qiniuBucketURLPrefix = options.domain;
+        }
+        config.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName
+    }
+
+    // 正式上传的前置方法,做预处理,应用七牛云配置
+    function upload(filePath, success, fail, options, progress, cancelTask) {
+        if (null == filePath) {
+            console.error('qiniu uploader need filePath to upload');
+            return;
+        }
+        if (options) {
+            updateConfigWithOptions(options);
+        }
+        if (config.qiniuUploadToken) {
+            doUpload(filePath, success, fail, options, progress, cancelTask);
+        } else if (config.qiniuUploadTokenURL) {
+            getQiniuToken(function () {
+                doUpload(filePath, success, fail, options, progress, cancelTask);
+            });
+        } else if (config.qiniuUploadTokenFunction) {
+            config.qiniuUploadToken = config.qiniuUploadTokenFunction();
+            if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
+                console.error('qiniu UploadTokenFunction result is null, please check the return value');
+                return
+            }
+            doUpload(filePath, success, fail, options, progress, cancelTask);
+        } else {
+            console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
+            return;
+        }
+    }
+
+    // 正式上传
+    function doUpload(filePath, success, fail, options, progress, cancelTask) {
+        if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
+            console.error('qiniu UploadToken is null, please check the init config or networking');
+            return
+        }
+        var url = uploadURLFromRegionCode(config.qiniuRegion);
+        var fileName = filePath.split('//')[1];
+        // 自定义上传key(即自定义上传文件名)。通过修改qiniuUploader.upload方法传入的options参数,可以进行自定义文件名称。如果options非空,则使用options中的key作为fileName
+        if (options && options.key) {
+            fileName = options.key;
+        }
+        var formData = {
+            'token': config.qiniuUploadToken
+        };
+        // qiniuShouldUseQiniuFileName 如果是 true,则文件的 key 由 qiniu 服务器分配(全局去重)。如果是 false,则文件的 key 使用微信自动生成的 filename。出于初代sdk用户升级后兼容问题的考虑,默认是 false。
+        if (!config.qiniuShouldUseQiniuFileName) {
+            formData['key'] = fileName
+        }
+		var source = 'h5';
+		//#ifdef APP-PLUS
+		source = 'app';
+		//#endif
+		
+		if (source == 'app') {
+			var uploader = plus.uploader.createUpload(url,{},function(up,state){
+				if( state== 200) {
+					var res = JSON.parse(up.responseText);
+					if (success) {
+					    success(res);
+					}
+				} else {
+					if (fail) {
+					    fail(state);
+					}
+				}
+			});
+			var num = 0;
+			var uploadInfo = {};
+			var uploadChangeInfo = function(upload, status) {
+				if (upload.state == 3) {
+					var count = (upload.uploadedSize / upload.totalSize)*100;
+					count = parseInt(count);
+					if (num != count) {
+						num = count;
+						
+						if (num % 10 == 0) {
+							uploadInfo.progress = num;
+							progress && progress(uploadInfo);
+						}
+					}
+				}
+			};
+			uploader.addEventListener("statechanged", uploadChangeInfo, false);
+			uploader.addData("key", fileName);  
+			uploader.addData("token",config.qiniuUploadToken);  
+			uploader.addFile(filePath,{"key":"file"});
+			uploader.start();
+		} else {
+			var uploadTask = uni.uploadFile({
+			    url: url,
+			    filePath: filePath,
+			    name: 'file',
+			    formData: formData,
+			    success: function (res) {
+			        var dataString = res.data
+			        //   // this if case is a compatibility with wechat server returned a charcode, but was fixed
+			        //   if(res.data.hasOwnProperty('type') && res.data.type === 'Buffer'){
+			        //     dataString = String.fromCharCode.apply(null, res.data.data)
+			        //   }
+			        try {
+			            var dataObject = JSON.parse(dataString);
+			            // 拼接fileURL
+			            var fileURL = config.qiniuBucketURLPrefix + '/' + dataObject.key;
+			            dataObject.fileURL = fileURL;
+			            // imageURL字段和fileURL字段重复,但本sdk不做删除,因为在最初版本使用的是imageURL。直接删除可能导致原有用户升级至新版sdk后出现异常。
+			            dataObject.imageURL = fileURL;
+			            console.log(dataObject);
+			            if (success) {
+			                success(dataObject);
+			            }
+			        } catch (e) {
+			            console.log('parse JSON failed, origin String is: ' + dataString)
+			            if (fail) {
+			                fail(e);
+			            }
+			        }
+			    },
+			    fail: function (error) {
+			        console.error(error);
+			        if (fail) {
+			            fail(error);
+			        }
+			    }
+			})
+			
+			// 文件上传进度
+			uploadTask.onProgressUpdate((res) => {
+			    progress && progress(res)
+			})
+			
+			// 中断文件上传
+			cancelTask && cancelTask(() => {
+			    uploadTask.abort()
+			})
+		}
+    }
+
+    // 获取七牛云uptoken, url为后端服务器获取七牛云uptoken接口
+    function getQiniuToken(callback) {
+        uni.request({
+            url: config.qiniuUploadTokenURL,
+            success: function (res) {
+                var token = res.data.uptoken;
+                if (token && token.length > 0) {
+                    config.qiniuUploadToken = token;
+                    if (callback) {
+                        callback();
+                    }
+                } else {
+                    console.error('qiniuUploader cannot get your token, please check the uptokenURL or server')
+                }
+            },
+            fail: function (error) {
+                console.error('qiniu UploadToken is null, please check the init config or networking: ' + error);
+            }
+        })
+    }
+
+    // 选择七牛云文件上传接口,文件向匹配的接口中传输。ECN, SCN, NCN, NA, ASG,分别对应七牛云的:华东,华南,华北,北美,新加坡 5 个区域
+    function uploadURLFromRegionCode(code) {
+        var uploadURL = null;
+        switch (code) {
+            case 'ECN': uploadURL = 'https://up.qiniup.com'; break;
+            case 'NCN': uploadURL = 'https://up-z1.qiniup.com'; break;
+            case 'SCN': uploadURL = 'https://up-z2.qiniup.com'; break;
+            case 'NA': uploadURL = 'https://up-na0.qiniup.com'; break;
+            case 'ASG': uploadURL = 'https://up-as0.qiniup.com'; break;
+            default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
+        }
+        return uploadURL;
+    }
+
+    module.exports = {
+        init: init,
+        upload: upload,
+    }
+})();

+ 1 - 1
lib/dever/config.js

@@ -8,7 +8,7 @@ const request = {
 	//	服务器接口地址
 
 	host: "http://192.168.2.70/dreamland/",
-	host: "http://192.168.3.66/dreamland/",
+	//host: "http://192.168.3.66/dreamland/",
 	
 	//	请求的参数	
 	data: {},

+ 95 - 68
lib/dever/index.js

@@ -273,7 +273,17 @@ var page = {
 }
 
 var upload = {
-	data : {},
+	data : {},
+	formatDate : function(date) {
+		var date = new Date(date);
+		var YY = date.getFullYear() + '-';
+		var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
+		var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
+		var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
+		var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
+		var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
+		return YY + MM + DD +" "+hh + mm + ss;
+	},
 	handle : function(key, count, callback) {
 		if (!count) {
 			count = 1;
@@ -405,71 +415,88 @@ var upload = {
 		}
 	},
 	
-	qiniu : function(qn, config, key, count, callback) {
-		if (!count) {
-			count = 1;
-		}
-		var type = 1;
-		if (count > 1) {
-			type = 2;
-		}
-		var self = this;
-		count = parseInt(count);
-		uni.chooseImage({
-			count: count,
-			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
-			sourceType: ['album'], //从相册选择
-			success: res => {
-				uni.showLoading();
-				res.tempFilePaths.forEach(function(item, index) {
-					//请求上传接口
-					qn.upload(
-						item,
-						res => {
-							dever.debug(res);
-							var data = res;
-							uni.hideLoading();
-							if (data.uploaded) {
-								var backUrl = data.url;
-								if (count > 1) {
-									if (!self.data[key]) {
-										self.data[key] = [];
-									}
-									self.data[key].push(backUrl);
-								} else {
-									self.data[key] = backUrl;
-								}
-								if (callback) {
-									callback(type, self.data[key]);
-								}
-							} else if (data.uploaded == false) {
-								uni.showToast({ title: data.error.message, icon: 'none' });
-							}
-						},
-						error => {
-							uni.showToast({ title: '图片上传失败,请重试', icon: 'none' });
-							uni.hideLoading();
-						},
-						{
-							region: 'ECN',
-							domain: config.upload,
-							//key: key,
-							uptoken: config.token
-						},
-						res => {
-								//上传进度
-							if(res.progress === 100){
-								//resolve(keys);
-							}
-						}
-					);
-				});
-			},
-			fail: () => {
-				uni.showToast({ title: '图片上传失败,请重试', icon: 'none' });
-				uni.hideLoading();
-			}
-		});
+	qnUpload : function(qn, config, key, count, callback) {
+		if (!count) {
+			count = 1;
+		}
+		var type = 1;
+		if (count > 1) {
+			type = 2;
+		}
+		var self = this;
+		count = parseInt(count);
+		var call = function(data) {
+			var backUrl = data.url;
+			if (count > 1) {
+				if (!self.data[key]) {
+					self.data[key] = [];
+				}
+				self.data[key].push(backUrl);
+			} else {
+				self.data[key] = backUrl;
+			}
+			if (callback) {
+				callback(type, self.data[key]);
+			}
+		}
+		uni.chooseImage({
+			count: count,
+			//sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
+			sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
+			sourceType: ['album'], //从相册选择
+			success: res => {
+				uni.showLoading();
+				res.tempFilePaths.forEach(function(item, index) {
+					self.qiniu(qn, item, config.domain, config.token, call);
+				});
+			},
+			fail: () => {
+				uni.showToast({ title: '图片上传失败,请重试', icon: 'none' });
+				uni.hideLoading();
+			}
+		});
+	},
+	
+	qiniu : function(qn, file, domain, token, call, handle) {
+		//请求上传接口
+		var config = {};
+		config = {
+			region: 'ECN',
+			domain: domain,
+			//key: 'test.mp4',
+		};
+		if (token.indexOf('http') == -1) {
+			config.uptoken = token;
+		} else {
+			config.uptokenURL = token;
+		}
+		uni.showLoading({title: '上传中', mask: true});
+		qn.upload(
+			file,
+			res => {
+				dever.debug(res);
+				var data = res;
+				uni.hideLoading();
+				if (data.uploaded) {
+					call(data);
+				} else {
+					uni.showToast({title: data.error.message, icon: 'none' });
+				}
+			},
+			error => {
+				uni.showToast({title: '上传失败,请重试', icon: 'none' });
+				uni.hideLoading();
+			},
+			config,
+			res => {
+				//上传进度
+				if (handle) {
+					handle(res.progress);
+				} else {
+					uni.showToast({title: '上传进度:%' + res.progress, icon: 'none' });
+				}
+			}
+		);
 	},
 	
 	uploadDel : function(key, index, callback) {
@@ -899,8 +926,8 @@ var dever = {
 	},
 	
 	//上传
-	qiniu : function(qn, self, id, count, callback) {
-		upload.qiniu(qn, self, id, count, callback);
+	qiniu : function(qn, self, id, count, callback, handle) {
+		upload.qiniu(qn, self, id, count, callback, handle);
 	},
 	
 	//上传文件

+ 127 - 0
pages/dream/test.vue

@@ -0,0 +1,127 @@
+<template>
+	<gracePage :customHeader="false">
+		<!-- 页面主体 -->
+		<view slot="gBody" class="grace-body">
+			<view class="grace-list-items">
+				<view class="grace-list-body grace-border-b">
+					<view class="grace-list-title" @tap="showDrawer1">
+						<text class="grace-list-title-text">左侧抽屉</text>
+						<text  class="grace-list-title-desc">点击测试</text>
+					</view>
+				</view>
+				<text class="grace-list-arrow-right grace-icons icon-arrow-right"></text>
+			</view>
+			<view class="grace-list-items">
+				<view class="grace-list-body grace-border-b">
+					<view class="grace-list-title" @tap="showDrawer2">
+						<text class="grace-list-title-text">右侧抽屉</text>
+						<text  class="grace-list-title-desc">点击测试</text>
+					</view>
+				</view>
+				<text class="grace-list-arrow-right grace-icons icon-arrow-right"></text>
+			</view>
+			<!-- 抽屉组件 左侧 -->
+			<graceDrawer :show="show1" top="0" width="100%" v-on:closeDrawer="closeDrawer1">
+				<view slot="links">
+					<view class="grace-list">
+						<view class="grace-list-items">
+							<text class="grace-list-icon grace-icons icon-comments grace-blue"></text>
+							<view class="grace-list-body grace-border-b">
+								<view class="grace-list-title" @tap="fun1">
+									<text class="grace-list-title-text">功能菜单</text>
+								</view>
+							</view>
+						</view>
+						<view class="grace-list-items">
+							<text class="grace-list-icon grace-icons icon-set grace-blue"></text>
+							<view class="grace-list-body grace-border-b">
+								<view class="grace-list-title" @tap="fun2">
+									<text class="grace-list-title-text">功能菜单</text>
+								</view>
+							</view>
+						</view>
+						<view style="text-align:center; padding:20px;">
+							您可以放置任何内容 ...
+						</view>
+					</view>
+				</view>
+			</graceDrawer>
+			<!-- 抽屉组件 右侧 -->
+			<graceDrawer :show="show2" v-on:closeDrawer="closeDrawer2" direction="right">
+				<view slot="links">
+					<view class="grace-list">
+						<view class="grace-list-items">
+							<text class="grace-list-icon grace-icons icon-comments grace-blue"></text>
+							<view class="grace-list-body grace-border-b">
+								<view class="grace-list-title" @tap="fun3">
+									<text class="grace-list-title-text">功能菜单</text>
+								</view>
+							</view>
+						</view>
+						<view class="grace-list-items">
+							<text class="grace-list-icon grace-icons icon-set grace-blue"></text>
+							<view class="grace-list-body grace-border-b">
+								<view class="grace-list-title" @tap="fun4">
+									<text class="grace-list-title-text">功能菜单</text>
+								</view>
+							</view>
+						</view>
+						<view style="text-align:center; padding:20px;">
+							您可以放置任何内容 ...
+						</view>
+					</view>
+				</view>
+			</graceDrawer>
+		</view>
+	</gracePage>
+</template>
+<script>
+import gracePage from "@/lib/graceUI/components/gracePage.vue";
+import graceDrawer from '@/lib/graceUI/components/graceDrawer.vue';
+export default {
+    data() {
+    	return {
+			show1 : false,
+			show2 : false
+		}
+    },
+	methods:{
+		// 左侧
+		showDrawer1 : function(){
+			this.show1 = true;
+		},
+		closeDrawer1 : function(){
+			this.show1 = false;
+		},
+		fun1 : function(){
+			this.closeDrawer1();
+			uni.showToast({title:"您点击了第1个导航", icon:"none"})
+		},
+		fun2 : function(){
+			this.closeDrawer1();
+			uni.showToast({title:"您点击了第2个导航", icon:"none"})
+		},
+		// 右侧
+		showDrawer2 : function(){
+			this.show2 = true;
+		},
+		closeDrawer2 : function(){
+			this.show2 = false;
+		},
+		fun3 : function(){
+			this.closeDrawer2();
+			uni.showToast({title:"您点击了第1个导航", icon:"none"})
+		},
+		fun4 : function(){
+			this.closeDrawer2();
+			uni.showToast({title:"您点击了第2个导航", icon:"none"})
+		},
+	},
+	components:{
+		gracePage, graceDrawer
+	}
+}
+</script>
+<style>
+
+</style>

+ 8 - 0
pages/dream/view/cate.vue

@@ -0,0 +1,8 @@
+<template>
+</template>
+
+<script>
+</script>
+
+<style>
+</style>