ajaxFileuplaod 是一个异步上传图片的插件
1.引入插件:
<script src="${ctxStatic}/js/ajaxfileupload.js" type="text/javascript"></script>
<script src="${ctxStatic}/js/jquery.min.js" type="text/javascript" ></script>
<script src="${ctxStatic}/js/bootstrap.min.js" type="text/javascript"></script>
2.jsp页面
<form action="" class="form-group" id="data-form" encType="multipart/form-data"/>
<label class="col-sm-2 control-label">图片地址:</label>
<div class="col-md-4">
<input class="form-control" id="adPicLink" name="adPicLink"
required type="text" style="width: 200px;" />
</div>
<label class="col-sm-2 control-label">活动地址:</label>
<div class="col-md-4">
<input class="form-control" id="adLink" name="adLink"
required type="text" style="width: 200px;" />
</div>
<label class="col-sm-2 control-label">活动状态:</label>
<div class="col-md-4">
<input class="form-control" id="adStatus" name="adStatus" required
type="text" style="width: 200px;" />
</div>
<label class="col-sm-2 control-label" id ="uploadLabel">图片上传:</label>
<div class="col-md-4">
<input id = "upload" name="upload" type="file" multiple="" />
</div>
</form>
*encType="multipart/form-data":当数据和图片一起上传时,一定要加
3.js方法
url = "${ctx}/${moduleName}/update.json?";
var params = "adName="+$("#adName").val()+"&adPicLink="+$("#adPicLink").val()//我试过用data:{“name”:“name”}传参数,后台取到的是null,我觉得只能用这样的传参方式,也许还有更好的
url = url +params;
$.ajaxFileUpload
(
{
url: url, //上传处理程序地址
type: 'post',// 请求方式
fileElementId: 'upload',//上传图片标签的Id
data:data(我觉得没用,建议不用加)
dataType: 'json',//服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
success: function (result)//服务器响应成功处理函数
error: function (data)//服务器响应失败处理函数
}
)
4.配置文件中配置
<!-- SpringMVC上传文件时,需配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过800KB......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="800000"/>
</bean>
5.后台Controller获取
@RequestMapping(value = "add", method = RequestMethod.POST)
public ModelAndView add(@FormModel TAdvertisement entity,HttpServletRequest request, @RequestParam(value = "upload") MultipartFile file) throws Exception {
ModelAndView mav = new ModelAndView("/demo2/show");
String fileName = file.getOriginalFilename();
String path =Thread.currentThread().getContextClassLoader().getResource("").toString();//获取项目路径
path=path.replace('/', '\\'); // 将/换成\
path=path.replace("WEB-INF\\classes\\", ""); //去掉class\
path=path.replace("file:", ""); //去掉file:
path=path.substring(1);
path=path+"images";
logger.debug("path================>" + path);
logger.debug("fileName==============>" + fileName);
File targetFile = new File(path, fileName);
file.transferTo(targetFile);
logger.debug(path);
advertisementService.addItem(entity);
mav.addObject("result", "SUCCESS");
return mav;
}
来源:https://www.cnblogs.com/mylogs/p/5085596.html