Parcourir la source

本地附件上传

Jianghan il y a 3 ans
Parent
commit
d1b9033c05

+ 83 - 41
src/service/repair_service.go

@@ -11,6 +11,7 @@ import (
 	"io/ioutil"
 	"log"
 	mu "mfw/util"
+	"mime/multipart"
 	"mongodb"
 	"net"
 	"net/http"
@@ -1153,6 +1154,7 @@ func (jy *RepairRule) UpFile() {
 	if jy.Method() == "POST" {
 		user := jy.GetSession("user").(map[string]interface{})
 		identity := jy.GetString("identity")
+		isCover, _ := jy.GetBool("isCover") // 是否覆盖已有附件
 		var id string
 		if len(identity) == 24 {
 			id = identity
@@ -1163,6 +1165,20 @@ func (jy *RepairRule) UpFile() {
 		}
 		qu.Debug("download --- url/id ---", id)
 		files := jy.GetString("files")
+		mf, err := jy.GetFiles()
+		if err != nil {
+			qu.Debug("File Received Failed:", err)
+			jy.ServeJson(map[string]interface{}{
+				"rep": false,
+				"msg": "附件上传失败",
+			})
+			return
+		}
+		fileMap := make(map[string]*multipart.File)
+		for _, hf := range mf {
+			f, _ := hf.Open()
+			fileMap[hf.Filename] = &f
+		}
 		var fileArr []map[string]interface{}
 		if err := json.Unmarshal([]byte(files), &fileArr); err != nil {
 			qu.Debug("UserInfo Unmarshal Failed:", err)
@@ -1177,16 +1193,30 @@ func (jy *RepairRule) UpFile() {
 		for _, m := range fileArr {
 			download := qu.ObjToString(m["org_url"])
 			filename := qu.ObjToString(m["filename"])
-			res, err := http.Get(download)
-			if err != nil {
-				qu.Debug("Download url error ---", download)
-				jy.ServeJson(map[string]interface{}{
-					"rep": false,
-					"msg": "文件下载失败",
-				})
-				return
+			var bt []byte
+			if download == "" {
+				f := fileMap[filename]
+				if f == nil {
+					qu.Debug("File find error ---" + filename)
+					jy.ServeJson(map[string]interface{}{
+						"rep": false,
+						"msg": "未找到文件",
+					})
+					return
+				}
+				bt, _ = ioutil.ReadAll(*f)
+			} else {
+				res, err := http.Get(download)
+				bt, _ = ioutil.ReadAll(res.Body)
+				if err != nil {
+					qu.Debug("Download url error ---", download)
+					jy.ServeJson(map[string]interface{}{
+						"rep": false,
+						"msg": "文件下载失败",
+					})
+					return
+				}
 			}
-			bt, _ := ioutil.ReadAll(res.Body)
 			key := GetHashKey(bt) + TypeByExt(filename)
 			b, err := OssPutObject(key, bytes.NewReader(bt))
 			if b {
@@ -1203,7 +1233,7 @@ func (jy *RepairRule) UpFile() {
 				qu.Debug("File upload error ---", err)
 				jy.ServeJson(map[string]interface{}{
 					"rep": false,
-					"msg": "文件上传失败",
+					"msg": "文件上传oss失败",
 				})
 				return
 			}
@@ -1215,47 +1245,59 @@ func (jy *RepairRule) UpFile() {
 		} else {
 			coll = "bidding_back"
 		}
-		info, _ := JYMgo.FindById(coll, id, map[string]interface{}{"projectinfo": 1})
-		if len(*info) > 0 {
-			if (*info)["projectinfo"] != nil {
-				if attsMap := (*info)["projectinfo"].(map[string]interface{}); attsMap["attachments"] != nil {
-					maps := attsMap["attachments"].(map[string]interface{})
-					max := 0
-					for k, _ := range maps {
-						if qu.IntAll(k) > max {
-							max = qu.IntAll(k)
+		if isCover {
+			tmp := make(map[string]interface{})
+			for i, att := range atts {
+				tmp[strconv.Itoa(i+1)] = att
+			}
+			attsmap := make(map[string]interface{})
+			attsmap["attachments"] = tmp
+			updateMap := make(map[string]interface{})
+			updateMap["projectinfo"] = attsmap
+			JYMgo.UpdateById(coll, id, map[string]interface{}{"$set": updateMap})
+		} else {
+			info, _ := JYMgo.FindById(coll, id, map[string]interface{}{"projectinfo": 1})
+			if len(*info) > 0 {
+				if (*info)["projectinfo"] != nil {
+					if attsMap := (*info)["projectinfo"].(map[string]interface{}); attsMap["attachments"] != nil {
+						maps := attsMap["attachments"].(map[string]interface{})
+						max := 0
+						for k, _ := range maps {
+							if qu.IntAll(k) > max {
+								max = qu.IntAll(k)
+							}
 						}
+						for i, att := range atts {
+							maps[strconv.Itoa(i+max+1)] = att
+						}
+						attsMap["attachments"] = maps
+					} else {
+						tmp := make(map[string]interface{})
+						for i, att := range atts {
+							tmp[strconv.Itoa(i+1)] = att
+						}
+						attsMap["attachments"] = tmp
 					}
-					for i, att := range atts {
-						maps[strconv.Itoa(i+max+1)] = att
-					}
-					attsMap["attachments"] = maps
+					delete(*info, "_id")
+					JYMgo.UpdateById(coll, id, map[string]interface{}{"$set": *info})
 				} else {
 					tmp := make(map[string]interface{})
 					for i, att := range atts {
 						tmp[strconv.Itoa(i+1)] = att
 					}
-					attsMap["attachments"] = tmp
+					attsmap := make(map[string]interface{})
+					attsmap["attachments"] = tmp
+					updateMap := make(map[string]interface{})
+					updateMap["projectinfo"] = attsmap
+					JYMgo.UpdateById(coll, id, map[string]interface{}{"$set": updateMap})
 				}
-				delete(*info, "_id")
-				JYMgo.UpdateById(coll, id, map[string]interface{}{"$set": *info})
 			} else {
-				tmp := make(map[string]interface{})
-				for i, att := range atts {
-					tmp[strconv.Itoa(i+1)] = att
-				}
-				attsmap := make(map[string]interface{})
-				attsmap["attachments"] = tmp
-				updateMap := make(map[string]interface{})
-				updateMap["projectinfo"] = attsmap
-				JYMgo.UpdateById(coll, id, map[string]interface{}{"$set": updateMap})
+				jy.ServeJson(map[string]interface{}{
+					"rep": false,
+					"msg": "id查询失败, " + id,
+				})
+				return
 			}
-		} else {
-			jy.ServeJson(map[string]interface{}{
-				"rep": false,
-				"msg": "id查询失败, " + id,
-			})
-			return
 		}
 
 		jy.ServeJson(map[string]interface{}{

+ 1 - 1
src/util/ossclient.go

@@ -13,7 +13,7 @@ import (
 )
 
 var (
-	ossEndpoint        = "oss-cn-beijing.aliyuncs.com" //正式环境用:oss-cn-beijing-internal.aliyuncs.com 测试:oss-cn-beijing.aliyuncs.com
+	ossEndpoint        = "oss-cn-beijing-internal.aliyuncs.com" //正式环境用:oss-cn-beijing-internal.aliyuncs.com 测试:oss-cn-beijing.aliyuncs.com
 	ossAccessKeyId     = "LTAI4G5x9aoZx8dDamQ7vfZi"
 	ossAccessKeySecret = "Bk98FsbPYXcJe72n1bG3Ssf73acuNh"
 	ossBucketName      = "jy-datafile" //jy-datafile

+ 16 - 4
src/web/templates/com/header.html

@@ -61,25 +61,25 @@
 		    </div>
 		    <div class="modal-body">
 		     	<div class="form-group">
-				    <label for="code" class="col-sm-2 control-label">账号:</label>
+				    <label class="col-sm-2 control-label">账号:</label>
 				    <div class="col-sm-10">
 						<input id="t_email" type="email" value={{(session "user").email}} class="form-control" disabled>
 				    </div>
 				</div>
 				<div class="form-group">
-				    <label for="code" class="col-sm-2 control-label">密码:</label>
+				    <label class="col-sm-2 control-label">密码:</label>
 				    <div class="col-sm-10">
 						<input id="t_pwd" type="password" value={{(session "user").pwd}} class="form-control" placeholder="请输入密码">
 				    </div>
 				</div>
 				<div class="form-group">
-				    <label for="site" class="col-sm-2 control-label">姓名:</label>
+				    <label class="col-sm-2 control-label">姓名:</label>
 				    <div class="col-sm-10">
 						<input id="t_name" type="text" value={{(session "user").name}} class="form-control" disabled>
 				    </div>
 				</div>
 				<div class="form-group">
-				    <label for="modify" class="col-sm-2 control-label">角色:</label>
+				    <label class="col-sm-2 control-label">角色:</label>
 				    <div class="col-sm-10">
 				     	<select id="t_role" class="form-control" disabled>
 							<option value={{(session "user").role}}>
@@ -127,4 +127,16 @@ function t_save(){
 		})
 	});
 }
+
+//展示loading框
+showLoading = function (text){
+	if(text){
+		$("#loadText").html(text)
+	}
+	$('#loadingModal').modal({backdrop: 'static', keyboard: false});
+}
+//隐藏掉loading框
+hideLoading = function (){
+	$('#loadingModal').modal('hide');
+}
 </script>

+ 119 - 27
src/web/templates/repair/jy_file_upload.html

@@ -23,17 +23,27 @@
                         <div class="col-sm-3">
                             <input type="text" class="form-control" id="identity" placeholder="剑鱼链接/数据ID" value="">
                         </div>
+                        <div style="width: auto">
+                            <label class="control-label">是否覆盖已有全部附件:</label>
+                            <input id="switch-cover-file" name="switch-pwd" type="checkbox">
+                        </div>
                     </div>
                     <div id="TaskDiv">
                         <div id="itemDiv" style="display: none">
                             <div class="form-group">
-                                <label class="col-sm-2 control-label">附件地址</label>
+                                <label class="col-sm-2 control-label" id="lab_name"></label>
                                 <div class="col-sm-5">
                                     <input type="text" class="furl form-control" placeholder="附件下载地址" value="">
                                 </div>
                             </div>
                             <div class="form-group">
-                                <label class="col-sm-2 control-label">附件名称</label>
+                                <label class="col-sm-2 control-label">本地文件:</label>
+                                <div class="col-sm-5">
+                                    <input type="file" name="file" class="ffile" id="uploadfile-add-0">
+                                </div>
+                            </div>
+                            <div class="form-group">
+                                <label class="col-sm-2 control-label">附件名称:</label>
                                 <div class="col-sm-5">
                                     <input type="text" class="fname form-control" placeholder="附件名称.类型" value="">
                                 </div>
@@ -42,13 +52,19 @@
                     </div>
                     <div class="group-item">
                         <div class="form-group">
-                            <label class="col-sm-2 control-label">附件地址</label>
+                            <label class="col-sm-2 control-label">附件一&nbsp;&nbsp;&nbsp;&nbsp;附件地址:</label>
                             <div class="col-sm-5">
                                 <input type="text" class="furl form-control" id="downloadurl" placeholder="附件下载地址" value="">
                             </div>
                         </div>
                         <div class="form-group">
-                            <label class="col-sm-2 control-label">附件名称</label>
+                            <label class="col-sm-2 control-label">本地文件:</label>
+                            <div class="col-sm-5">
+                                <input type="file" name="file" class="ffile" id="uploadfile-add">
+                            </div>
+                        </div>
+                        <div class="form-group">
+                            <label class="col-sm-2 control-label">附件名称:</label>
                             <div class="col-sm-5">
                                 <input type="text" class="fname form-control" id="filename" placeholder="附件名称.类型" value="">
                             </div>
@@ -78,6 +94,9 @@
 <script>
     menuActive("/service/jy/repair/upfile");
 
+    let addNum = 1
+    let isCover = false     //附件覆盖
+
     $(document).ready(function () {
         ttable = $('#dataTable').dataTable({
             "paging": true,
@@ -109,54 +128,84 @@
                 });
             },
             "columns": [
-                {"data": null},
-                {"data": "infoid"},
+                {"data": null, width: "3%"},
+                {"data": "infoid", width: "8%"},
                 {"data": "value"},
                 {"data": "createtime", render: function (val) {
                         var dt = new Date()
                         dt.setTime(parseInt(val) * 1000);
                         return dt.format("yyyy-MM-dd hh:mm")
                     }},
-                {"data": "modifyuser"}
+                {"data": "modifyuser", "defaultContent": ""}
             ]
         });
     });
 
+    $('#switch-cover-file').bootstrapSwitch({
+        onText : "是",
+        offText : "否",
+        onColor : "success",
+        offColor : "warning",
+    }).bootstrapSwitch('size', 'small').bootstrapSwitch('state', false);
+    $('#switch-cover-file').bootstrapSwitch('onSwitchChange', function (event, state){isCover = state})
+
     function addFile() {
         let tNode = $('#itemDiv').clone().addClass('group-item').addClass('clone-template').show()
-        $('#TaskDiv').append($(tNode))
+        addNum += 1
+        $(tNode).find('#lab_name').html("附件"+toChinesNum(addNum)+"&nbsp;&nbsp;&nbsp;&nbsp;附件地址:")
+        $('#TaskDiv').prepend($(tNode))
     }
 
     function upload() {
         let identity = $('#identity').val()
         if (identity === "") {
             showMsg("请填写剑鱼url或者数据id")
-            return
+            return;
         }
         let arr = []
-        $('.group-item').each(function () {
-            let furl = $(this).find("input.furl").val()
-            if (furl === undefined) {
-                showTip("请填写附件下载地址")
-                return
-            }
-            let fname = $(this).find("input.fname").val()
-            if (fname === "") {
-                showTip("请填写附件名称和文件类型")
-                return
-            }
-            let tmp = {}
-            tmp["org_url"] = furl
-            tmp["filename"] = fname
-            arr.push(tmp)
-        })
+        let fData = new FormData();
+        fData.append("identity", identity)
+        fData.append("isCover", isCover)
+        try {
+            $('.group-item').each(function () {
+                let furl = $(this).find("input.furl").val()
+                let fFile = $(this).find('input.ffile')[0].files[0]
+                if (furl === "" && fFile === undefined) {
+                    throw "请填写附件下载地址或选择本地文件";
+                }
+                let fName = $(this).find("input.fname").val()
+                if (fName === "") {
+                    throw "请填写附件名称和文件类型"
+                }
+                let tmp = {}
+                tmp["filename"] = fName
+                tmp["org_url"] = furl
+                if (fFile !== undefined) {
+                    fData.append("file", fFile, fName)
+                }
+                arr.push(tmp)
+            })
+        } catch(e){
+            showTip(e);
+            return;
+        }
+        if (arr.length > 0) {
+            fData.append("files", JSON.stringify(arr))
+        }
+        showLoading("正在上传附件,请稍候...")
         $.ajax({
             url: "/service/jy/repair/upfile",
             type: 'POST',
-            data: {"identity": identity, "files": JSON.stringify(arr)},
+            data: fData,
+            cache: false,
+            processData: false,
+            contentType: false,
             success: function (r) {
+                hideLoading()
                 if (r.rep) {
-                    ttable.api().ajax.reload();
+                    showTip("附件上传成功", function (){
+                        ttable.api().ajax.reload();
+                    })
                 } else {
                     showTip(r.msg);
                 }
@@ -164,4 +213,47 @@
         })
     }
 
+    /**
+     * 数字转成汉字
+     * @params num === 要转换的数字
+     * @return 汉字
+     * */
+    function toChinesNum(num) {
+        let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
+        let unit = ['', '十', '百', '千', '万']
+        num = parseInt(num)
+        let getWan = (temp) => {
+            let strArr = temp.toString().split('').reverse()
+            let newNum = ''
+            let newArr = []
+            strArr.forEach((item, index) => {
+                newArr.unshift(item === '0' ? changeNum[item] : changeNum[item] + unit[index])
+            })
+            let numArr = []
+            newArr.forEach((m, n) => {
+                if (m !== '零') numArr.push(n)
+            })
+            if (newArr.length > 1) {
+                newArr.forEach((m, n) => {
+                    if (newArr[newArr.length - 1] === '零') {
+                        if (n <= numArr[numArr.length - 1]) {
+                            newNum += m
+                        }
+                    } else {
+                        newNum += m
+                    }
+                })
+            } else {
+                newNum = newArr[0]
+            }
+
+            return newNum
+        }
+        let overWan = Math.floor(num / 10000)
+        let noWan = num % 10000
+        if (noWan.toString().length < 4) {
+            noWan = '0' + noWan
+        }
+        return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
+    }
 </script>