1:文件上传需要依赖commons-io-2.2.jar和commons-fileupload-1.3.1.jar包
2:配置springmvc-context.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.myhome.base.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/mypage/" />
<property name="suffix" value=".html" />
</bean>
<!-- 文件上传的配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1024000000"></property>
</bean>
</beans>
3:后台Java文件
package com.myhome.base.controller;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.myhome.base.entity.User;
import com.myhome.base.enums.Gender;
import com.myhome.base.service.CarPortService;
import com.myhome.base.service.PropertyCostService;
import com.myhome.base.service.UserService;
import com.myhome.core.system.InitData;
import com.myhome.core.util.Utility;
/**
* <p>创建时间: 2016年3月4日</p>
* @author kin.liufu
* @describe 住户的逻辑处理类
*/
@Scope("prototype")
@RequestMapping("/mypage/")
@Controller
public class UserController {
@Resource
private UserService userService;
@Resource
private CarPortService carPortService;
@Resource
private PropertyCostService propertyCostService;
/**
* @describe此方法接口用户完善信息
*/
@RequestMapping(produces = "text/plain;charset=UTF-8", value = "userUpDateMSG")
@ResponseBody
// 如果是多个文件上传的话,那么需要@RequestParam MultipartFile[] upLoadImage,而且@RequestParam这个一定不能少,所以一般都是加上去的好
// public String userUpDateMSG(HttpServletRequest request, String phoneNum, String securityQuestionOne, String securityQuestionTwo, String answerOne, String answerTwo, String gender, @RequestParam MultipartFile[] upLoadImage){
public String userUpDateMSG(HttpServletRequest request, String phoneNum, String securityQuestionOne, String securityQuestionTwo, String answerOne, String answerTwo, String gender, MultipartFile upLoadImage){
String ERRTIP = "";
HashMap<String, String> hashMap = new HashMap<>();
if(request.getSession().getAttribute("USERINFO") == null){
ERRTIP = "TIMEOUTOFLOGIN";
hashMap.put("ERRTIP", ERRTIP);
}else{
String relativePath = "";
User user = (User) request.getSession().getAttribute("USERINFO");
String fileName = upLoadImage.getOriginalFilename();
if(!Utility.isStringEmpty(fileName)){
relativePath = "USER/Imges/headImages/" + Utility.formatDateToString(new Date(), "YYYY-MM-dd") + "\\" + System.currentTimeMillis() + "~" + (int)(Math.random()*100) + Utility.getTypeOfFile(fileName);
File targetFile = new File(InitData.outPutPath, relativePath);
if(!targetFile.exists()){
targetFile.mkdirs();
//保存
try {
upLoadImage.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
user.setHeadImagePath(relativePath);
}
if("man".equals(gender)){
user.setGender(Gender.MAN);
}else{
user.setGender(Gender.WOMAN);
}
user.setPhoneNumber(phoneNum);
user.setSecurityQuestionOne(securityQuestionOne);
user.setSecurityQuestionTwo(securityQuestionTwo);
user.setAnswerOne(answerOne);
user.setAnswerTwo(answerTwo);
if(!userService.update(user)){
ERRTIP = "头像更新到数据库时,出现了错误";
hashMap.put("ERRTIP", ERRTIP);
}
}
return JSONObject.toJSONString(hashMap);
}
}
4:最后是web前端如何把信息推送上来,有两种方式:
1==>最简单的form表单直接发送,简单,但是不能接受后台返回来的数据,不知道操作有没有成功,无法进行进一步的操作。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>uploadFile</title>
</head>
<body>
<!-- 必须要设置enctype="multipart/form-data" method="post",否则会提示:The current request is not a multipart request -->
<!-- 本人在这里熬了好几个小时,真烦!!!!! -->
<form action="uploadfile.do" enctype="multipart/form-data" method="post">
<input type="file" name="upLoadImage"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
2:==>现在比较流行的jquery $.ajaxFileUpload({}); 这需要借助jquery库,最大的优点:ajax能够接收后台返回来的数据,这样我们就可以根据后台返回来的数据进行进一步的操作和判断
<script src="lib/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="lib/ajaxfileupload.js" type="text/javascript"></script>
//数据是不能够在外面定义的,只能在里面直接定义
// var data111{
// phoneNum : $("#phoneNum").val().trim(),
// describe : $("#describe").val().trim(),
// gender : $("input:radio:checked").val().trim()
// }
$("#upDateMsgOfManager").click(function(){
$.ajaxFileUpload({
url : 'managerUpDateMSG.do',
secureuri: false,
fileElementId: 'upLoadImage',
//一般不要选中dataType,有jquery库来判断,否则的话,很容易会触发error: function (result) {}
//dataType: 'json',
data: {//加入的文本参数 ,必须写在这里不能够用下面的哪种方式
phoneNum : $("#phoneNum").val().trim(),
describe : $("#describe").val().trim(),
gender : $("input:radio:checked").val().trim()
},
// data : data111, //要传送数据的话,需要在这里构造,而不能够在外面构造再放进来
success: function (result) {
if(isStrEmpty(result.ERRTIP)){
alert("信息修改成功!");
loadUserInfo();
}else if("TIMEOUTOFLOGIN" == data.ERRTIP.trim()){
alert("登陆超时,请重新登陆");
location.href="sign-in.html";
}else{
alert(result.ERRTIP);
}
},
error: function (result) {
location.href="sign-in.html";
}
});
return false;
});
总结:文件上传有两种方式,第二种相对来说用的比较多