注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

kangzye的博客

加Q群25382780切磋java,加19360923群研究JavaScript

 
 
 

日志

 
 

jquery 异步不刷新页面 ajax方式上传图片  

2012-02-21 09:51:02|  分类: javascript |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
此中方式是使用 jquery.form.js ,可以方便的让form表单已ajax方式提交,form中可包含多个属性值以及多个上传文件。
代码如下:
html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://kangzye.blog.163.com/blog/inc/jquery.1.4.2.js"></script>
<script type="text/javascript" src="http://kangzye.blog.163.com/blog/inc/jquery.form.js"></script>
</head>
<body>
<form action="uploadFile.do?t=22" method="post" name="form1" id="form1" enctype="multipart/form-data">
<input type="file" name="uploadify" id="uploadify"/>
<input type="file" name="uploadify2" id="uploadify2"/>
<input type="text" name="username" value="admin" /><input name="trueName" type="text" value="他搜房额" />

<input type="button" id="submitBtn" value="submit"/>
</form>

<script>
$(document).ready(function(){
$('#submitBtn').click(function(){
$('#form1').ajaxSubmit(function(data){
alert(data);
});
});
});
</script>
</body>
</html>


java:
Action:

public class UploadFileAction extends ActionSupport implements ModelDriven{
private UploadFileActionForm form = new UploadFileActionForm();
public Object getModel(){
return form;
}

public String upload(){
File file = new File("D:/test/"+form.getUploadifyFileName());
File file2 = new File("D:/test/"+form.getUploadify2FileName());
System.out.println(form.getUsername());
System.out.println(form.getTrueName());
try{
copyToFile(form.getUploadify(), file);
copyToFile(form.getUploadify2(), file2);
ServletActionContext.getResponse().getWriter().write("true");
}catch (Exception e) {
e.printStackTrace();

try {
ServletActionContext.getResponse().getWriter().write("false");
} catch (IOException e1) {
e1.printStackTrace();
}
}
return null;
}

private void copyToFile(File from ,File to)throws Exception{
FileInputStream in = new FileInputStream(from);
FileOutputStream out = new FileOutputStream(to);
byte[] bs = new byte[10240];
int c = 0;
while((c=in.read(bs))!=-1){
out.write(bs,0,c);
}
in.close();
out.flush();
out.close();
}
}

actionForm:

public class UploadFileActionForm {
private String uploadifyFileName;
private String uploadifyContentType;
private File uploadify;
private Integer uploadifyFileSize;
private File uploadify2;
private String uploadify2FileName;
private String uploadify2ContentType;
private String username;
private String trueName;

//getter & setter...

}

  评论这张
 
阅读(8912)| 评论(4)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017