前言
这两天可是把我给折磨惨了,本来以为新给我的任务就只是一个增删改查,很快就能搞定,可是!!!!栽在了上传文件这里了。把我给折磨得全身通透,舒舒服服啊!好吧,搞定之后心有余悸,生怕下次再在这里栽跟头,于是乎记录一下。
我们现在的框架是在spring框架下,使用jsp画页面,我同事使用的是表单直接提交的方式,提交完成后跳转到一个公用的成功界面,该页面弹出提示信息,emm…我看了一下,不是我想要的效果,我觉得还是使用Ajax提交,在本页面提示信息就好了。
一、前端部分
HTML
前端使用的是bootstrap框架,样式看着还可以,至少上传文件这一块我觉得很不错了。
type设置为file,multiple表示可以多文件上传,data-show-upload="false"是bootstrap的,禁用有一个上传按钮的。
<div class="form-group">
<label for="editor-container" class="col-sm-2 control-label no-padding-right">
<i style="color: red;">* </i>现场照片
</label>
<div class="col-sm-8">
<!-- 上传附件 -->
<input id="file-0a" class="file" name="files" type="file" multiple data-show-upload="false">
</div>
</div>
<div class="cdiv">
<button type="button" class="btn btn-primary" id="btn_savebb">保存新增</button>
<button type="button" class="btn btn-default" id="btn_exit">退出</button>
</div>
JS
js这一块也不难,简单分析一下。
var formData = new FormData($("#form0")[0]);//是创建formData,form0是表单的id,[0]很重要,必须要加,不然会报错的。
data : formData,//这里是直接将formData赋给data
processData : false,//processData默认为true(该方法为jQuery独有的)
默认情况下会将发送的数据序列化以适应默认的内容类型application/x-www-form-urlencoded
如果想发送不想转换的的信息的时候需要手动将其设置为false
contentType : false,//不设置内容类型
//保存
$("#btn_savebb").click(function(){
var formData = new FormData($("#form0")[0]);
var url="${_path}/glpt/sgjg/addInfo";
if(checkForm()){
$.ajax({
type : 'POST',
url : url,
data : formData,
dataType : 'json',
async: false,
cache : false,
processData : false,
contentType : false,
error : function(xhr, status, statusText) {
layer.msg("网络错误!" + xhr.status);
},
success : function(data) {
if (data.res == 'ok') {
layer.alert(data.msg, {icon : 6},
function(index2){
ifok();
});
} else {
layer.alert('保存失败', {icon : 3});
}
}
});
}
});
二、java
因为懒就没有简化,直接将项目里的一部分拷过来了,
首先,设置为post方式,我这里使用PostMapping,也可以使用RequestMapping设置method,因为不是传过来的内容类型不是application/json,所以不能使用@RequestBody,只能一个个去接收,因为是多文件,这里使用MultipartFile[] files,其他的就是对文件的处理。
这里的文件是放在一个子表中,没有放在信息表里,这种方式顺便在此记录一下。
@PostMapping(value="addInfo")
@ResponseBody
public Map<String, Object> addInfo(MultipartFile[] files,
String fx,String cd,String zhk,String zhm,String sgmc,String sgxh,String xcqk,String iswg,String jgr,String jgrmc,String jgsj) throws IOException{
Map<String, Object> _out = new HashMap<String, Object>();
Users user = (Users) req.getSession().getAttribute(Constant.SESSION_USER);
SgjgEntity entity = new SgjgEntity();
entity.setCjr(user.getYhdh());//创建人
entity.setXh(sjAqjcDao.getXh());//获取序号
entity.setFx(fx);
entity.setCd(cd);
entity.setZhk(zhk);
entity.setZhm(zhm);
entity.setSgmc(sgmc);
entity.setSgxh(sgxh);
entity.setXcqk(xcqk);
entity.setIswg(iswg);
entity.setJgr(jgr);
entity.setJgrmc(jgrmc);
entity.setJgsj(jgsj);
//声明参数
int upNum = 0;//上传文件数量
int saveNum = 0;//保存文件数量
String fileName = "";//文件名
String path = Constant.UPLOAD_FILEPATH + "sjsgjg\\" + entity.getXh() + "\\";
String url = Constant.UPLOAD_FILEURL + "sjsgjg/" + entity.getXh() + "/";
//获取实体中的文件,上传文件并持久化
if(files!=null){
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
if(!file.isEmpty()){//文件非空
upNum++;
//确保父文件夹存在
File tmpFile = new File(path);
if(!tmpFile.exists()){
tmpFile.mkdirs();
}
//获取文件名
String realName = file.getOriginalFilename();
//获取文件后缀
String suffix = realName.substring(realName.lastIndexOf("."),realName.length());//eg:.png/.jpg/...
//获取uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
//保存文件
fileName = uuid+suffix;//文件名
File newfile = new File(path+fileName);//创建文件
file.transferTo(newfile);//复制文件
//将图片信息存入附件表
SjZp zp = new SjZp();
zp.setZbbh(entity.getXh());
zp.setZblb("sgjg");
zp.setZpurl(url + fileName);
zp.setZplb("1");
zp.setZppath(path + fileName);
int res = sjZpDao.saveSjZp(zp);
if (res == 0) {
saveNum++;
}
}
}
}
boolean b = sgjgDao.add(entity);
if(b){
_out.put("res", "ok");
_out.put("msg", "信息保存成功!含上传文件"+saveNum+"个");
}else{
_out.put("res", "error");
_out.put("msg", "信息保存失败!");
}
return _out;
}
效果图
没啥效果图,按着步骤来就能成功!