submit方式: 1 <form id="postForm" name="postForm" action="${rc.contextPath}/backdoor/uploadGroovy/upload" 2 enctype="multipart/form-data" method="post"> ...
submit方式:
1 <form id="postForm" name="postForm" action="${rc.contextPath}/backdoor/uploadGroovy/upload" 2 enctype="multipart/form-data" method="post"> 3 <table style="font-size:14px;" class="tablelist" align="center"> 4 <th> 5 選擇上傳的zip: 6 </th> 7 <th><input id="file" type="file" name="file"> 8 </th> 9 <th> 10 <div> 11 <button type="button" onclick="uploadFile()">上傳</button> 12 </div> 13 </th> 14 </table> 15 </form>View Code
1 <script type="text/javascript"> 2 function uploadFile() { 3 var file = document.getElementById("file").value; 4 if (file == '') { 5 alert('請選擇上傳的文件!'); 6 return; 7 } 8 document.getElementById("postForm").submit(); 9 } 10 </script>View Code
ajax方式:
1 <form id="postForm" name="postForm" action="${rc.contextPath}/backdoor/uploadGroovy/upload" 2 enctype="multipart/form-data" method="post"> 3 <table style="font-size:14px;" class="tablelist" align="center"> 4 <th> 5 選擇上傳的zip: 6 </th> 7 <th><input id="file" type="file" name="file"> 8 </th> 9 <th> 10 <div> 11 <button type="button" onclick="uploadFile()">上傳</button> 12 </div> 13 </th> 14 </table> 15 </form>View Code
1 <script type="text/javascript"> 2 function uploadFile() { 3 if (confirm("您確定要上傳嗎!")) { 4 var file = document.getElementById("file").value; 5 if (file == '') { 6 alert('請選擇上傳的文件!'); 7 return; 8 } 9 var fileName = $("#file").val(); 10 var fileTypes = new Array("zip"); //定義可支持的文件類型數組 11 var fileTypeFlag = "0"; 12 var newFileName = fileName.split('.'); 13 newFileName = newFileName[newFileName.length - 1]; 14 for (var i = 0; i < fileTypes.length; i++) { 15 if (fileTypes[i] == newFileName) { 16 fileTypeFlag = "1"; 17 } 18 } 19 if (fileTypeFlag == "0") { 20 alert("上傳文件必須是zip格式!"); 21 return; 22 } 23 $.ajax({ 24 url: "${rc.contextPath}/backdoor/uploadGroovy/upload", 25 type: "post", 26 data: new FormData($('#postForm')[0]), 27 processData: false, 28 contentType: false, 29 success: function (data) { 30 if (data.code == 1) { 31 window.location.href = "${rc.contextPath}/backdoor/deploy/queryDeploy"; 32 } else { 33 alert(data.message); 34 } 35 } 36 }); 37 } 38 } 39 </script>View Code
總結:使用FormData的對象進行Ajax方式上傳文件。
具體用法是:使用 new FormData($('#postForm')[0]) 方式傳遞參數
服務端解析代碼:
1 package cn.fraudmetrix.octopus.horai.web.controller; 2 3 import cn.fraudmetrix.octopus.horai.biz.service.backdoor.UploadGroovyService; 4 import cn.fraudmetrix.octopus.horai.client.Result; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.RequestMethod; 9 import org.springframework.web.bind.annotation.RequestParam; 10 import org.springframework.web.bind.annotation.ResponseBody; 11 import org.springframework.web.multipart.MultipartFile; 12 13 14 /** 15 * Created by hunt on 2017/7/31. 16 * 上傳腳本、模板 17 */ 18 @Controller 19 @RequestMapping("uploadGroovy") 20 public class UploadGroovyController { 21 @Autowired 22 UploadGroovyService uploadGroovyService; 23 24 @ResponseBody 25 @RequestMapping(value = "upload", method = RequestMethod.POST) 26 public Object uploadZip(@RequestParam(value = "file") MultipartFile file) { 27 Result result = new Result(); 28 if (file.isEmpty()) { 29 String str = "file is empty"; 30 result.setCode(-1); 31 result.setMessage(str); 32 return result; 33 } 34 try { 35 result = uploadGroovyService.uploadZip(file); 36 } catch (Exception e) { 37 result.setCode(-1); 38 result.setMessage(e.getMessage()); 39 e.printStackTrace(); 40 } 41 return result; 42 } 43 }View Code
1 package cn.fraudmetrix.octopus.horai.biz.service.backdoor; 2 3 import cn.fraudmetrix.octopus.horai.base.constants.ModuleConstants; 4 import cn.fraudmetrix.octopus.horai.base.constants.OperateConstants; 5 import cn.fraudmetrix.octopus.horai.biz.config.ShutterItemConfig; 6 import cn.fraudmetrix.octopus.horai.biz.utils.ListUtil; 7 import cn.fraudmetrix.octopus.horai.biz.utils.Md5Util; 8 import cn.fraudmetrix.octopus.horai.client.Result; 9 import cn.fraudmetrix.octopus.horai.dal.dao.CleanRuleDAO; 10 import cn.fraudmetrix.octopus.horai.dal.dao.ConfigDeployDAO; 11 import cn.fraudmetrix.octopus.horai.dal.dao.TemplateDAO; 12 import cn.fraudmetrix.octopus.horai.dal.po.*; 13 import com.alibaba.fastjson.JSON; 14 import org.apache.commons.io.IOUtils; 15 import org.springframework.beans.factory.annotation.Autowired; 16 import org.springframework.stereotype.Service; 17 import org.springframework.transaction.annotation.Transactional; 18 import org.springframework.util.CollectionUtils; 19 import org.springframework.web.multipart.MultipartFile; 20 21 import javax.annotation.Resource; 22 import java.io.File; 23 import java.io.IOException; 24 import java.security.NoSuchAlgorithmException; 25 import java.util.*; 26 import java.util.regex.Matcher; 27 import java.util.regex.Pattern; 28 import java.util.zip.ZipEntry; 29 import java.util.zip.ZipInputStream; 30 31 /** 32 * Created by hunt on 2017/7/31. 33 */ 34 @Service 35 public class UploadGroovyService { 36 37 @Autowired 38 private CleanRuleDAO cleanRuleDAO; 39 40 @Autowired 41 private TemplateDAO templateDAO; 42 43 @Autowired 44 private ConfigDeployDAO configDeployDAO; 45 46 @Autowired 47 private LogService logService; 48 49 @Resource 50 private ShutterItemConfig shutterItemConfig; 51 52 public Result uploadZip(MultipartFile multipartFile) throws Exception { 53 //校驗是否有待載入項或者已載入但是未發佈的 54 Result result = new Result(); 55 long count = configDeployDAO.queryByStatusAndEnv(); 56 if (count > 0) { 57 result.setCode(-1); 58 result.setMessage("上傳失敗:有待載入、未發佈的數據"); 59 return result; 60 } 61 62 List<UploadGroovyDO> uploadRuleList = new ArrayList<>(); 63 List<UploadVmDO> uploadTemplateList = new ArrayList<>(); 64 Map<Integer, UploadVmDO> templateMap = new HashMap<>(); 65 ZipInputStream zipInputStream = new ZipInputStream(multipartFile.getInputStream()); 66 ZipEntry zipEntry; 67 while ((zipEntry = zipInputStream.getNextEntry()) != null) { 68 if (!zipEntry.isDirectory()) { 69 String content = IOUtils.toString(zipInputStream, "UTF-8"); 70 String entryName = zipEntry.getName(); 71 String[] entryNames = entryName.split(File.separator, 2); 72 entryName = entryNames[1]; 73 String[] names = entryName.split(File.separator); 74 UploadGroovyDO uploadGroovyDO = new UploadGroovyDO(); 75 if ("groovy".equals(names[0])) {//載入腳本 76 uploadGroovyDO.setName(names[1].split("\\.")[0]); 77 if ("groovy".equals(names[1].split("\\.")[1])) { 78 uploadGroovyDO.setContent(content); 79 uploadRuleList.add(uploadGroovyDO);//遍歷之後uploadList是所有上傳的腳本集合 80 } 81 } 82 if ("template".equals(names[0])) {//載入模板 83 String templateNames = names[1].split("\\.")[0]; 84 if ("vm".equals(names[1].split("\\.")[1])) { 85 String[] templateName = templateNames.split("_"); 86 int id = Integer.parseInt(templateName[0]); 87 String name = templateName[1]; 88 boolean flag = templateName.length == 3; 89 if (!templateMap.containsKey(id)) { 90 UploadVmDO newVmDO = new UploadVmDO(); 91 newVmDO.setId(id); 92 newVmDO.setName(name); 93 templateMap.put(id, newVmDO); 94 } 95 UploadVmDO vmDO = templateMap.get(id); 96 if (flag) { 97 vmDO.setReason(content); 98 } else { 99 vmDO.setContent(content); 100 } 101 } 102 } 103 } 104 } 105 106 //Map轉List 107 Iterator it = templateMap.keySet().iterator(); 108 while (it.hasNext()) { 109 Integer key = (Integer) it.next(); 110 uploadTemplateList.add(templateMap.get(key)); 111 } 112 113 if (uploadRuleList.size() == 0 || uploadTemplateList.size() == 0) { 114 result.setCode(-1); 115 result.setMessage("上傳失敗:腳本、模板不能為空"); 116 return result; 117 } 118 119 List<UploadGroovyDO> mysqlRuleList = cleanRuleDAO.selectAllRule();//資料庫中所有腳本集合 120 List<UploadVmDO> mysqlTemplateList = templateDAO.selectAllTemplate();//資料庫中所有模板集合 121 122 //比較入庫 123 saveRuleAndTemplate(uploadRuleList, mysqlRuleList, uploadTemplateList, mysqlTemplateList); 124 125 mysqlRuleList = cleanRuleDAO.selectAllRule();//插入後資料庫中所有腳本集合 126 mysqlTemplateList = templateDAO.selectAllTemplate();//插入後資料庫中所有模板集合 127 128 //上傳的腳本和庫中再次比較 129 if (uploadRuleList.size() != mysqlRuleList.size() || uploadTemplateList.size() != mysqlTemplateList.size()) { 130 result.setCode(-1); 131 result.setMessage("上傳失敗:上傳腳本、模板和資料庫中個數不一致"); 132 return result; 133 } 134 //對list排序 135 Collections.sort(uploadRuleList); 136 Collections.sort(mysqlRuleList); 137 Collections.sort(uploadTemplateList); 138 Collections.sort(mysqlTemplateList); 139 140 for (int i = 0; i < uploadRuleList.size(); i++) { 141 if (!compareMd5(uploadRuleList.get(i).getContent(), mysqlRuleList.get(i).getContent())) { 142 result.setCode(-1); 143 result.setMessage("上傳失敗:上傳腳本和資料庫中內容不一致"); 144 return result; 145 } 146 } 147 148 for (int i = 0; i < uploadTemplateList.size(); i++) { 149 if (!compareMd5(uploadTemplateList.get(i).getContent() + uploadTemplateList.get(i).getReason(), 150 mysqlTemplateList.get(i).getContent() + mysqlTemplateList.get(i).getReason())) { 151 result.setCode(-1); 152 result.setMessage("上傳失敗:上傳模板和資料庫中內容不一致"); 153 return result; 154 } 155 } 156 157 result.setCode(1); 158 result.setMessage("success"); 159 return result; 160 } 161 162 @Transactional 163 private void saveRuleAndTemplate(List<UploadGroovyDO> uploadRuleList, List<UploadGroovyDO> mysqlRuleList, 164 List<UploadVmDO> uploadTemplateList, List<UploadVmDO> mysqlTemplateList) throws Exception { 165 166 //是否還有編輯項 167 List<ConfigDeploy> configDeployList = configDeployDAO.queryByStatus(); 168 int nextVersion = (int) configDeployDAO.nextVersion(); 169 if (!CollectionUtils.isEmpty(configDeployList)) { 170 //刪除編輯的記錄 171 configDeployDAO.batchDeleteConfigDeploy(configDeployList); 172 } 173 174 //插入發佈記錄 175 ConfigDeploy configDeploy = new ConfigDeploy(); 176 configDeploy.setVersion(nextVersion); 177 configDeploy.setDeployStatus((short) 0); 178 configDeploy.setBakStatus((short) 0); 179 configDeploy.setDeployType((short) 0); 180 configDeploy.setEnv(shutterItemConfig.getEnv()); 181 configDeployDAO.insertSelective(configDeploy); 182 183 //比較上傳腳本和資料庫中腳本的情況 184 //新增情況 185 List<UploadGroovyDO> addRuleList = ListUtil.diff(uploadRuleList, mysqlRuleList); 186 //刪除情況 187 List<UploadGroovyDO> deleteRuleList = ListUtil.diff(mysqlRuleList, uploadRuleList); 188 //修改情況 189 List<UploadGroovyDO> commonUploadRuleList = ListUtil.intersect(uploadRuleList, mysqlRuleList);//返回的是upload集合 190 List<UploadGroovyDO> commonMysqlRuleList = ListUtil.intersect(mysqlRuleList, uploadRuleList);//返回的是mysql集合 191 192 //對list排序 193 Collections.sort(commonUploadRuleList); 194 Collections.sort(commonMysqlRuleList); 195 196 List<UploadGroovyDO> updateRuleList = new ArrayList<>(); 197 for (int i = 0; i < commonUploadRuleList.size(); i++) { 198 boolean flag = compareMd5(commonUploadRuleList.get(i).getContent(), commonMysqlRuleList.get(i).getContent()); 199 if (!flag) { 200 updateRuleList.add(commonUploadRuleList.get(i)); 201 } 202 } 203 //批量新增addRuleList 204 if (addRuleList != null && addRuleList.size() > 0) { 205 List<CleanRule> batchInsertRules = new ArrayList<>(addRuleList.size()); 206 batchInsertRules = convertBeanC(batchInsertRules, addRuleList); 207 cleanRuleDAO.batchInsertRules(batchInsertRules); 208 //操作日誌介面 209 String[] ruleNames = new String[batchInsertRules.size()]; 210 for (int i = 0; i < batchInsertRules.size(); i++) { 211 ruleNames[i] = batchInsertRules.get(i).getRuleName(); 212 } 213 logService.saveLog(ModuleConstants.DEPLOY, OperateConstants.ADD + JSON.toJSONString(ruleNames), false); 214 } 215 216 217 //批量刪除deleteRuleList 218 if (deleteRuleList != null && deleteRuleList.size() > 0) { 219 List<CleanRule> batchDeleteRules = new ArrayList<>(deleteRuleList.size()); 220 batchDeleteRules = convertBeanC(batchDeleteRules, deleteRuleList); 221 cleanRuleDAO.batchDeleteRules(batchDeleteRules); 222 //操作日誌介面 223 String[] ruleNames = new String[batchDeleteRules.size()]; 224 for (int i = 0; i < batchDeleteRules.size(); i++) { 225 ruleNames[i] = batchDeleteRules.get(i).getRuleName(); 226 } 227 logService.saveLog(ModuleConstants.DEPLOY, OperateConstants.DELETE + JSON.toJSONString(ruleNames), false); 228 } 229 230 231 //修改updateRuleList 232 if (updateRuleList != null && updateRuleList.size() > 0) { 233 List<CleanRule> batchUpdateRules = new ArrayList<>(updateRuleList.size()); 234 batchUpdateRules = convertBeanC(batchUpdateRules, updateRuleList); 235 String[] ruleNames = new String[batchUpdateRules.size()]; 236 for (int i = 0; i < batchUpdateRules.size(); i++) { 237 cleanRuleDAO.updateByName(batchUpdateRules.get(i)); 238 ruleNames[i] = batchUpdateRules.get(i).getRuleName(); 239 } 240 logService.saveLog(ModuleConstants.DEPLOY, OperateConstants.UPDATE + JSON.toJSONString(ruleNames), false); 241 } 242 243