在ssm项目中要实现文件上传功能首先要导入俩个jar包
commons-fileupload.jar和commons-io.jar
然后需要在前端页面上使用
并且需要用表单,表单的enctype设为multipart/form-data
例如
[code]
修改头像
然后需要在js中获得表单对象
同时需要使用FormData对象序列化
[code]
$('#upload').change(function(){ //当upload对象改变时执行函数
var form=document.getElementById('ff');
var f=new FormData(form)//创建FormDate对象 FormDate对象会直接将(upload对象)name作为key,文件作为value
})
$('#upload').change(function(){ //当upload对象改变时执行函数
var file=document.getElementById('upload').files[0];
var f=new FormData()//创建FormDate对象
f.append("name",file)
})
以上俩种方式都是在f中放入文件
然后使用ajax访问controller处理
ajax.js代码
[code]var oAjax;
function ajax (url,data,success){
console.log(data);
oAjax=new XMLHttpRequest();
oAjax.onreadystatechange=function(){
if (oAjax.readyState==4){
if(oAjax.status==200){
success(oAjax.responseText);
}
else{
alert("请求出错请刷新后再试");
}
}
}
if(data==""){
oAjax.open('GET',url,true);
oAjax.send();
}
else{
oAjax.open('POST',url,false);
if(typeof(data)=='string'){
oAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
}
oAjax.send(data);
}
}
下面直接使用ajax函数访问
[code]
$('#upload').change(function(){ //当upload对象改变时执行函数
var url="../user/upload";
var form=document.getElementById('ff');
var f=new FormData(form)//创建FormDate对象 FormDate对象会直接将(upload对象)name作为key,文件作为value
ajax(url,f,function(date){
var img=JSON.parse(date);
var i=document.getElementById("tim");
i.src="../images/"+img.image
})
})
ajax会将前台的请求转到controller定位到url
后台使用MultipartFile 接收前面传过来的文件
在使用时需要在application-contenxt.xml中配置如果没有配置会报错
[code]
[code]@RequestMapping("upload")
@ResponseBody
public Map upload(@RequestParam(value = "file") MultipartFile file,HttpServletRequest request,String im) throws IOException{
String b=request.getSession().getServletContext().getRealPath("/");
String username=(String) request.getSession().getAttribute("username");
b=b.replaceAll("\\\\","/");
byte[] a=file.getBytes();
String name1=file.getOriginalFilename();
String ims[]=name1.split("\\.");
ims[0]=im;
String name=ims[0]+"."+ims[1];
String image=user.savefile(b,a,name);
user u=user.query(username);
String path=u.getImage();
user.deletefile(path);
u.setImage(image);
user.update(u);
Map m=new HashMap();
m.put("image",name);
return m;
}