文件上传submit、ajax方式

时间:2021-04-07 16:01:12

submit方式:

 <form id="postForm" name="postForm" action="${rc.contextPath}/backdoor/uploadGroovy/upload"
enctype="multipart/form-data" method="post">
<table style="font-size:14px;" class="tablelist" align="center">
<th>
选择上传的zip:
</th>
<th><input id="file" type="file" name="file">
</th>
<th>
<div>
<button type="button" onclick="uploadFile()">上传</button>
</div>
</th>
</table>
</form>
 <script type="text/javascript">
function uploadFile() {
var file = document.getElementById("file").value;
if (file == '') {
alert('请选择上传的文件!');
return;
}
document.getElementById("postForm").submit();
}
</script>

ajax方式:

 <form id="postForm" name="postForm" action="${rc.contextPath}/backdoor/uploadGroovy/upload"
enctype="multipart/form-data" method="post">
<table style="font-size:14px;" class="tablelist" align="center">
<th>
选择上传的zip:
</th>
<th><input id="file" type="file" name="file">
</th>
<th>
<div>
<button type="button" onclick="uploadFile()">上传</button>
</div>
</th>
</table>
</form>
 <script type="text/javascript">
function uploadFile() {
if (confirm("您确定要上传吗!")) {
var file = document.getElementById("file").value;
if (file == '') {
alert('请选择上传的文件!');
return;
}
var fileName = $("#file").val();
var fileTypes = new Array("zip"); //定义可支持的文件类型数组
var fileTypeFlag = "0";
var newFileName = fileName.split('.');
newFileName = newFileName[newFileName.length - 1];
for (var i = 0; i < fileTypes.length; i++) {
if (fileTypes[i] == newFileName) {
fileTypeFlag = "1";
}
}
if (fileTypeFlag == "0") {
alert("上传文件必须是zip格式!");
return;
}
$.ajax({
url: "${rc.contextPath}/backdoor/uploadGroovy/upload",
type: "post",
data: new FormData($('#postForm')[0]),
processData: false,
contentType: false,
success: function (data) {
if (data.code == 1) {
window.location.href = "${rc.contextPath}/backdoor/deploy/queryDeploy";
} else {
alert(data.message);
}
}
});
}
}
</script>

总结:使用FormData的对象进行Ajax方式上传文件。

具体用法是:使用 new FormData($('#postForm')[0]) 方式传递参数

服务端解析代码:

 package cn.fraudmetrix.octopus.horai.web.controller;

 import cn.fraudmetrix.octopus.horai.biz.service.backdoor.UploadGroovyService;
import cn.fraudmetrix.octopus.horai.client.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; /**
* Created by hunt on 2017/7/31.
* 上传脚本、模板
*/
@Controller
@RequestMapping("uploadGroovy")
public class UploadGroovyController {
@Autowired
UploadGroovyService uploadGroovyService; @ResponseBody
@RequestMapping(value = "upload", method = RequestMethod.POST)
public Object uploadZip(@RequestParam(value = "file") MultipartFile file) {
Result result = new Result();
if (file.isEmpty()) {
String str = "file is empty";
result.setCode(-1);
result.setMessage(str);
return result;
}
try {
result = uploadGroovyService.uploadZip(file);
} catch (Exception e) {
result.setCode(-1);
result.setMessage(e.getMessage());
e.printStackTrace();
}
return result;
}
}
 package cn.fraudmetrix.octopus.horai.biz.service.backdoor;

 import cn.fraudmetrix.octopus.horai.base.constants.ModuleConstants;
import cn.fraudmetrix.octopus.horai.base.constants.OperateConstants;
import cn.fraudmetrix.octopus.horai.biz.config.ShutterItemConfig;
import cn.fraudmetrix.octopus.horai.biz.utils.ListUtil;
import cn.fraudmetrix.octopus.horai.biz.utils.Md5Util;
import cn.fraudmetrix.octopus.horai.client.Result;
import cn.fraudmetrix.octopus.horai.dal.dao.CleanRuleDAO;
import cn.fraudmetrix.octopus.horai.dal.dao.ConfigDeployDAO;
import cn.fraudmetrix.octopus.horai.dal.dao.TemplateDAO;
import cn.fraudmetrix.octopus.horai.dal.po.*;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; /**
* Created by hunt on 2017/7/31.
*/
@Service
public class UploadGroovyService { @Autowired
private CleanRuleDAO cleanRuleDAO; @Autowired
private TemplateDAO templateDAO; @Autowired
private ConfigDeployDAO configDeployDAO; @Autowired
private LogService logService; @Resource
private ShutterItemConfig shutterItemConfig; public Result uploadZip(MultipartFile multipartFile) throws Exception {
//校验是否有待加载项或者已加载但是未发布的
Result result = new Result();
long count = configDeployDAO.queryByStatusAndEnv();
if (count > 0) {
result.setCode(-1);
result.setMessage("上传失败:有待加载、未发布的数据");
return result;
} List<UploadGroovyDO> uploadRuleList = new ArrayList<>();
List<UploadVmDO> uploadTemplateList = new ArrayList<>();
Map<Integer, UploadVmDO> templateMap = new HashMap<>();
ZipInputStream zipInputStream = new ZipInputStream(multipartFile.getInputStream());
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
if (!zipEntry.isDirectory()) {
String content = IOUtils.toString(zipInputStream, "UTF-8");
String entryName = zipEntry.getName();
String[] entryNames = entryName.split(File.separator, 2);
entryName = entryNames[1];
String[] names = entryName.split(File.separator);
UploadGroovyDO uploadGroovyDO = new UploadGroovyDO();
if ("groovy".equals(names[0])) {//加载脚本
uploadGroovyDO.setName(names[1].split("\\.")[0]);
if ("groovy".equals(names[1].split("\\.")[1])) {
uploadGroovyDO.setContent(content);
uploadRuleList.add(uploadGroovyDO);//遍历之后uploadList是所有上传的脚本集合
}
}
if ("template".equals(names[0])) {//加载模板
String templateNames = names[1].split("\\.")[0];
if ("vm".equals(names[1].split("\\.")[1])) {
String[] templateName = templateNames.split("_");
int id = Integer.parseInt(templateName[0]);
String name = templateName[1];
boolean flag = templateName.length == 3;
if (!templateMap.containsKey(id)) {
UploadVmDO newVmDO = new UploadVmDO();
newVmDO.setId(id);
newVmDO.setName(name);
templateMap.put(id, newVmDO);
}
UploadVmDO vmDO = templateMap.get(id);
if (flag) {
vmDO.setReason(content);
} else {
vmDO.setContent(content);
}
}
}
}
} //Map转List
Iterator it = templateMap.keySet().iterator();
while (it.hasNext()) {
Integer key = (Integer) it.next();
uploadTemplateList.add(templateMap.get(key));
} if (uploadRuleList.size() == 0 || uploadTemplateList.size() == 0) {
result.setCode(-1);
result.setMessage("上传失败:脚本、模板不能为空");
return result;
} List<UploadGroovyDO> mysqlRuleList = cleanRuleDAO.selectAllRule();//数据库中所有脚本集合
List<UploadVmDO> mysqlTemplateList = templateDAO.selectAllTemplate();//数据库中所有模板集合 //比较入库
saveRuleAndTemplate(uploadRuleList, mysqlRuleList, uploadTemplateList, mysqlTemplateList); mysqlRuleList = cleanRuleDAO.selectAllRule();//插入后数据库中所有脚本集合
mysqlTemplateList = templateDAO.selectAllTemplate();//插入后数据库中所有模板集合 //上传的脚本和库中再次比较
if (uploadRuleList.size() != mysqlRuleList.size() || uploadTemplateList.size() != mysqlTemplateList.size()) {
result.setCode(-1);
result.setMessage("上传失败:上传脚本、模板和数据库中个数不一致");
return result;
}
//对list排序
Collections.sort(uploadRuleList);
Collections.sort(mysqlRuleList);
Collections.sort(uploadTemplateList);
Collections.sort(mysqlTemplateList); for (int i = 0; i < uploadRuleList.size(); i++) {
if (!compareMd5(uploadRuleList.get(i).getContent(), mysqlRuleList.get(i).getContent())) {
result.setCode(-1);
result.setMessage("上传失败:上传脚本和数据库中内容不一致");
return result;
}
} for (int i = 0; i < uploadTemplateList.size(); i++) {
if (!compareMd5(uploadTemplateList.get(i).getContent() + uploadTemplateList.get(i).getReason(),
mysqlTemplateList.get(i).getContent() + mysqlTemplateList.get(i).getReason())) {
result.setCode(-1);
result.setMessage("上传失败:上传模板和数据库中内容不一致");
return result;
}
} result.setCode(1);
result.setMessage("success");
return result;
} @Transactional
private void saveRuleAndTemplate(List<UploadGroovyDO> uploadRuleList, List<UploadGroovyDO> mysqlRuleList,
List<UploadVmDO> uploadTemplateList, List<UploadVmDO> mysqlTemplateList) throws Exception { //是否还有编辑项
List<ConfigDeploy> configDeployList = configDeployDAO.queryByStatus();
int nextVersion = (int) configDeployDAO.nextVersion();
if (!CollectionUtils.isEmpty(configDeployList)) {
//删除编辑的记录
configDeployDAO.batchDeleteConfigDeploy(configDeployList);
} //插入发布记录
ConfigDeploy configDeploy = new ConfigDeploy();
configDeploy.setVersion(nextVersion);
configDeploy.setDeployStatus((short) 0);
configDeploy.setBakStatus((short) 0);
configDeploy.setDeployType((short) 0);
configDeploy.setEnv(shutterItemConfig.getEnv());
configDeployDAO.insertSelective(configDeploy); //比较上传脚本和数据库中脚本的情况
//新增情况
List<UploadGroovyDO> addRuleList = ListUtil.diff(uploadRuleList, mysqlRuleList);
//删除情况
List<UploadGroovyDO> deleteRuleList = ListUtil.diff(mysqlRuleList, uploadRuleList);
//修改情况
List<UploadGroovyDO> commonUploadRuleList = ListUtil.intersect(uploadRuleList, mysqlRuleList);//返回的是upload集合
List<UploadGroovyDO> commonMysqlRuleList = ListUtil.intersect(mysqlRuleList, uploadRuleList);//返回的是mysql集合 //对list排序
Collections.sort(commonUploadRuleList);
Collections.sort(commonMysqlRuleList); List<UploadGroovyDO> updateRuleList = new ArrayList<>();
for (int i = 0; i < commonUploadRuleList.size(); i++) {
boolean flag = compareMd5(commonUploadRuleList.get(i).getContent(), commonMysqlRuleList.get(i).getContent());
if (!flag) {
updateRuleList.add(commonUploadRuleList.get(i));
}
}
//批量新增addRuleList
if (addRuleList != null && addRuleList.size() > 0) {
List<CleanRule> batchInsertRules = new ArrayList<>(addRuleList.size());
batchInsertRules = convertBeanC(batchInsertRules, addRuleList);
cleanRuleDAO.batchInsertRules(batchInsertRules);
//操作日志接口
String[] ruleNames = new String[batchInsertRules.size()];
for (int i = 0; i < batchInsertRules.size(); i++) {
ruleNames[i] = batchInsertRules.get(i).getRuleName();
}
logService.saveLog(ModuleConstants.DEPLOY, OperateConstants.ADD + JSON.toJSONString(ruleNames), false);
} //批量删除deleteRuleList
if (deleteRuleList != null && deleteRuleList.size() > 0) {
List<CleanRule> batchDeleteRules = new ArrayList<>(deleteRuleList.size());
batchDeleteRules = convertBeanC(batchDeleteRules, deleteRuleList);
cleanRuleDAO.batchDeleteRules(batchDeleteRules);
//操作日志接口
String[] ruleNames = new String[batchDeleteRules.size()];
for (int i = 0; i < batchDeleteRules.size(); i++) {
ruleNames[i] = batchDeleteRules.get(i).getRuleName();
}
logService.saveLog(ModuleConstants.DEPLOY, OperateConstants.DELETE + JSON.toJSONString(ruleNames), false);
} //修改updateRuleList
if (updateRuleList != null && updateRuleList.size() > 0) {
List<CleanRule> batchUpdateRules = new ArrayList<>(updateRuleList.size());
batchUpdateRules = convertBeanC(batchUpdateRules, updateRuleList);
String[] ruleNames = new String[batchUpdateRules.size()];
for (int i = 0; i < batchUpdateRules.size(); i++) {
cleanRuleDAO.updateByName(batchUpdateRules.get(i));
ruleNames[i] = batchUpdateRules.get(i).getRuleName();
}
logService.saveLog(ModuleConstants.DEPLOY, OperateConstants.UPDATE + JSON.toJSONString(ruleNames), false);
} //比较上传模板和数据库中模板的情况
//新增情况
List<UploadVmDO> addTemplateList = ListUtil.diff(uploadTemplateList, mysqlTemplateList);
//删除情况
List<UploadVmDO> deleteTemplateList = ListUtil.diff(mysqlTemplateList, uploadTemplateList);
//修改情况
List<UploadVmDO> commonUploadTemplateRuleList = ListUtil.intersect(uploadTemplateList, mysqlTemplateList);//返回的是upload集合
List<UploadVmDO> commonMysqlTemplateList = ListUtil.intersect(mysqlTemplateList, uploadTemplateList);//返回的是mysql集合 //对list排序
Collections.sort(commonUploadTemplateRuleList);
Collections.sort(commonMysqlTemplateList); List<UploadVmDO> updateTemplateList = new ArrayList<>();
for (int i = 0; i < commonUploadTemplateRuleList.size(); i++) {
boolean flag = compareMd5(commonUploadTemplateRuleList.get(i).getContent() + commonUploadTemplateRuleList.get(i).getReason(),
commonMysqlTemplateList.get(i).getContent() + commonMysqlTemplateList.get(i).getReason());
if (!flag) {
updateTemplateList.add(commonUploadTemplateRuleList.get(i));
}
}
//批量新增addTemplateList
if (addTemplateList != null && addTemplateList.size() > 0) {
List<TemplateDO> batchInsertTemplates = new ArrayList<>(addTemplateList.size());
batchInsertTemplates = convertBeanT(batchInsertTemplates, addTemplateList);
templateDAO.batchInsertTemplates(batchInsertTemplates);
//操作日志接口
String[] templateNames = new String[batchInsertTemplates.size()];
for (int i = 0; i < batchInsertTemplates.size(); i++) {
templateNames[i] = batchInsertTemplates.get(i).getName();
}
logService.saveLog(ModuleConstants.DEPLOY, OperateConstants.ADD + JSON.toJSONString(templateNames), false);
} //批量删除deleteTemplateList
if (deleteTemplateList != null && deleteTemplateList.size() > 0) {
List<TemplateDO> batchDeleteTemplates = new ArrayList<>(deleteTemplateList.size());
batchDeleteTemplates = convertBeanT(batchDeleteTemplates, deleteTemplateList);
templateDAO.batchDeleteTemplates(batchDeleteTemplates);
//操作日志接口
String[] templateNames = new String[batchDeleteTemplates.size()];
for (int i = 0; i < batchDeleteTemplates.size(); i++) {
templateNames[i] = batchDeleteTemplates.get(i).getName();
}
logService.saveLog(ModuleConstants.DEPLOY, OperateConstants.DELETE + JSON.toJSONString(templateNames), false);
} //修改updateTemplateList
if (updateTemplateList != null && updateTemplateList.size() > 0) {
List<TemplateDO> batchUpdateTemplates = new ArrayList<>(updateTemplateList.size());
batchUpdateTemplates = convertBeanT(batchUpdateTemplates, updateTemplateList);
String[] templateNames = new String[batchUpdateTemplates.size()];
for (int i = 0; i < batchUpdateTemplates.size(); i++) {
templateDAO.updateByName(batchUpdateTemplates.get(i));
templateNames[i] = batchUpdateTemplates.get(i).getName();
}
logService.saveLog(ModuleConstants.DEPLOY, OperateConstants.UPDATE + JSON.toJSONString(templateNames), false);
} } /**
* 比较MD5值
*
* @param string1
* @param string2
* @return
* @throws NoSuchAlgorithmException
*/
private boolean compareMd5(String string1, String string2) throws NoSuchAlgorithmException {
if (Md5Util.getMd5(string1).equals(Md5Util.getMd5(string2))) {
return true;
} else {
return false;
}
} /**
* UploadGroovyDO转换成CleanRule
*
* @param list1
* @param list2
* @return
*/
private List<CleanRule> convertBeanC(List<CleanRule> list1, List<UploadGroovyDO> list2) {
for (UploadGroovyDO uploadGroovyDO : list2) {
CleanRule cleanRule = new CleanRule();
cleanRule.setRuleName(uploadGroovyDO.getName());
cleanRule.setRuleContent(uploadGroovyDO.getContent());
cleanRule.setDescrib(getDescrib(uploadGroovyDO.getContent()));
cleanRule.setGmtCreate(new Date());
list1.add(cleanRule);
}
return list1;
} /**
* UploadGroovyDO转换成TemplateDO
*
* @param list1
* @param list2
* @return
*/
private List<TemplateDO> convertBeanT(List<TemplateDO> list1, List<UploadVmDO> list2) {
for (UploadVmDO uploadVmDO : list2) {
TemplateDO templateDO = new TemplateDO();
templateDO.setTemplateId(uploadVmDO.getId());
templateDO.setName(uploadVmDO.getName());
templateDO.setTemplateData(uploadVmDO.getContent());
templateDO.setTemplateReason(uploadVmDO.getReason());
templateDO.setGmtCreate(new Date());
list1.add(templateDO);
}
return list1;
} /**
* 获取描述内容
*
* @param string
* @return
*/
private String getDescrib(String string) {
Pattern regexDecrement = Pattern.compile("describ:([\\s\\S]*)###");//([\s\S]*)完全通配
Matcher matcher = regexDecrement.matcher(string);
if (matcher.find()) {
return matcher.group(1);
}
return null;
} }

外部拓展:SpringMVC上传文件的三种方式