1.在jsp页面<head>标签内引入script文件(注意顺序)
<script type="text/javascript" src="resources/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="resources/js/ajaxFileUpload.js"></script>
2.springMVC.xml配置文件中(必须进行配置)
<!--使用springMVC上传图片 ajaxFileUpload-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760" />
</bean>
3.<input>标签(id属性,<script>中 ajaxFileUpload的fileElementId会用到)
<input type="file" id="headImg" name="headImg"/>
4.在<script>标签中,我将ajaxFileUpload写在一个函数里,在需要用到上传图片的位置,调用该函数
function headImgUpload(){ //图片上传函数
var results = "";
var account = $("#account").val(); //account、identity 这两个变量,根据我的需求会在后面用到,阅读者可以根据自己的需求删掉或者修改这两个变量
var identity = $("input[name='identity']:checked").val();
$.ajaxFileUpload({
url:"register/headImgUpload?account="+account+"&identity="+identity,//根据url访问controller层中的方法
secureuri:false,
fileElementId:"headImg", //<input>标签中的id属性
type:"POST",
dataType:"text", //服务器返回的数据类型
success:function (result) {
result = result.replace(/<pre.*?>/g, ''); //ajaxFileUpload会对服务器响应回来的text内容加上<pre >text</pre>前后缀
result = result.replace(/<PRE.*?>/g, '');
result = result.replace("<PRE>", '');
result = result.replace("</PRE>", '');
result = result.replace("<pre>", '');
result = result.replace("</pre>", '');
result = JSON.parse(result);//转换为json格式
results = result.result;
alert(result);
},
error:function (data,status,error) {
alert("失败!!!"+error);
}
});
}
5.controller层
@Controller
@RequestMapping(value = "register")
public class RegisterController {
//用户头像上传
@RequestMapping(value = "/headImgUpload",method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> headImgUpload(@RequestParam MultipartFile headImg, String account, String identity, HttpServletRequest request){
//上传的结果
String result = "fail";
//头像上传到的位置
String imgRealPath = "";
try{
//确保上传的图片不为空
if(headImg != null && !headImg.isEmpty()){
//判断注册用户的身份,商户还是会员
if(identity.equals("member")){
//会员
imgRealPath = request.getSession().getServletContext().getRealPath("/resources/image/member");
}else if(identity.equals("businessman")){
//商户
imgRealPath = request.getSession().getServletContext().getRealPath("/resources/image/businessman");
}
System.out.println(imgRealPath);//在控制台打印一下路径
//上传完成后保存的文件名
String fileName= account + ".jpg";
//文件夹不存在的话,新建一个
File fileFolder = new File(imgRealPath);
if(!fileFolder.exists()){
fileFolder.mkdirs();
}
File file = new File(fileFolder,fileName);
//transferTo(),springMVC的方法,用于图片上传时,将内存中的图片写入磁盘
headImg.transferTo(file);//会报IO异常
result = "success";
}
}catch (IOException e){
e.printStackTrace();
}
Map<String,Object> resultMap = new HashMap<String,Object>();
resultMap.put("result",result);
return resultMap;
}
}
总结
以上所述是小编给大家介绍的springMVC使用ajaxFailUpload上传图片,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对天达云网站的支持!