JavaWeb项目中使用ajax上传文件

时间:2020-12-16 06:40:23

1.jsp

$("#cxsc").click(function(){
var bankId = $("#bankId").val();
var formdata = new FormData();
formdata.append('logo', $('#btnFile').get(0).files[0]);
formdata.append('bankId', bankId);
$.ajax({
type: 'POST',
url: './uploadLogo',
contentType : false,
data : formdata,
processData : false,
dataType: "json",
success: function (data) {
$("#logoImg").attr('src','${_b}/upload/banklogo/'+data.msg);
},
error : function(data) {
alert('上传失败!');
}
}); <#if formData?exists>
<#if (formData.logoImg??)>
<img src="${_b}/upload/banklogo/${formData.logoImg}" style="width:120px;height:120px;margin-bottom:5px;" id="logoImg"/>
<br/>
<input type="file" name="logo" id="btnFile" style="border:none;display:inline">
<button type="button" id="cxsc" style="display:inline">上传</button>
<#else>
<input type="file" name="logo" style="border:none">
</#if>
<#else>
<input type="file" name="logo" style="border:none">
</#if>

2.controller

@RequestMapping(value = "/uploadLogo", method = {RequestMethod.POST})
public void uploadLogo(
@RequestParam(value = "bankId", required = true) String bankId,
@RequestParam("logo") MultipartFile logo,
HttpServletRequest request, HttpServletResponse response, ModelMap model) {
Json json = new Json();
BankManage bankManage = bankManageService.getById(bankId);
if (bankManage != null) {
try {
if (!logo.isEmpty()) {
String relativePath = "/upload/banklogo";
// 旧图片路径
String absolutePath = request.getSession().getServletContext().getRealPath(relativePath)+"\\"+bankManage.getLogoImg();
File oldfile = new File(absolutePath);
if (oldfile.exists()) {
oldfile.delete(); // 删除旧图片
}
String newPath = request.getSession().getServletContext().getRealPath(relativePath)+"\\"+logo.getOriginalFilename();
File newFile = new File(newPath);
logo.transferTo(newFile);
bankManage.setLogoImg(logo.getOriginalFilename());
bankManageService.update(bankManage);
json.setMsg(logo.getOriginalFilename());
writeJson(request, response, json);
}else {
json.setMsg("上传失败!");
writeJson(request, response, json);
}
}catch (Exception e) {
e.printStackTrace();
logger.error(e);
}
}
}