文件上傳submit、ajax方式

来源:http://www.cnblogs.com/hunt/archive/2017/08/11/7346861.html
-Advertisement-
Play Games

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 
	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 這篇博文我們介紹兩方面:如何修改setting.xml文件及相應配置(本文maven版本為3.5.0) (1)首先打開maven文件目錄--conf,會看見如下目錄 (2)複製setting.xml文件,粘貼至預設目錄C:\用戶\用戶名\.m2文件中 對於初學者在安裝配置好maven之後,發現目錄下 ...
  • 對日期的一些操作: ...
  • 運行效果如下: 點擊文件按鈕,點擊打開菜單項,選擇一個文本文件,效果如下: 打開後,內容顯示如下: 對內容稍作修改,另存為名為sss的文件,效果如下: ...
  • 1.方法的重寫(Override):重新寫、覆蓋 1)發生在父子類中,方法名稱相同,參數列表相同,方法體不同 2)重寫方法被調用時,看對象的類型2.重寫與重載的區別: 1)重寫(Override): 1.1)發生在父子類中,方法名稱相同,參數列表相同,方法體不同 1.2)遵循"運行期綁定",看對象的 ...
  • 一、 Python介紹 Python(英國發音:/ˈpaɪθən/ 美國發音:/ˈpaɪθɑːn/), 是一種面向對象的解釋型電腦程式設計語言,由荷蘭人Guido van Rossum於1989年發明,第一個公開發行版發行於1991年。 Python是純粹的自由軟體, 源代碼和解釋器CPython ...
  • 1 package cn.fraudmetrix.octopus.horai.biz.utils; 2 3 import org.springframework.util.StringUtils; 4 5 import java.util.regex.Matcher; 6 import java.u ...
  • 1 package cn.fraudmetrix.octopus.horai.biz.utils; 2 3 import java.security.MessageDigest; 4 import java.security.NoSuchAlgorithmException; 5 6 public ...
  • 1 package cn.fraudmetrix.octopus.horai.biz.utils; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.Collections; 6 import ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...