java图片上传遇到的问题_Javaweb关于图片上传问题

在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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值