struts2+jquery+ajax实现上传&&校验实例
一直以为ajax不能做上传,直到最近看了一些文章。需要引入AjaxFileUploaderV2.1.zip,下载链接:http://pan.baidu.com/s/1i3L7I2T
代码和相关配置如下:
js代码:
<script>
//ajax 无刷新上传文件
function ajaxFileUpload() {
//判断是否选择文件
if($("#uploadFile").val() == null || $("#uploadFile").val()==""){
alert("请选择需要上传的文件!");
return;
}
//判断后缀名
var filepath=$("#uploadFile").val();
var extStart=filepath.lastIndexOf(".");
var ext=filepath.substring(extStart,filepath.length).toUpperCase();
if(".xls".toUpperCase() !=ext ){
alert("只能上传Excel97-2003工作簿文件(xls)");
return false;
}
//判断文件大小
var file = $('#uploadFile').get(0).files[0];
if (file) {
var fileSize = 0;
if (file.size > 2*1024 * 1024) {
alert("上传的文件大小不能超过2MB,请核对后重试!");
return false;
}
}
$("#loading")
.ajaxStart(function () {
$(this).show();
})//开始上传文件时显示一个图片
.ajaxComplete(function () {
$(this).hide();
});//文件上传完成将图片隐藏起来
$.ajaxFileUpload
(
{
url: '<%=request.getContextPath()%>/server/doUploadAndInsert.action',//用于文件上传的服务器端请求地址
secureuri: false,//一般设置为false
fileElementId: 'uploadFile',//文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'json',//返回值类型 一般设置为json
success: function (result) {
var msgBean = result;
alert(msgBean.msgText);
}
});
return false;
}
</script>
需要导入jquery星河ajaxfileupload.js,html代码:
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery-1.7.2.min.js"></script>
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery-ui.min.js"></script>
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery.validate.min.js"></script>
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery.metadata.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>
<div id="page-content" class="clearfix" style="padding-top: 20">
<form id="myform" enctype="multipart/form-data" method="post"
action="<%=request.getContextPath()%>/server/doUploadAndInsert.action">
<span style="font-size: 15px;">
选择文件<span style="color: #c91523">(*.xls格式)</span>: </span>
<input id="uploadFile" type="file" style="font-size: 15px" label="浏览" name="uploadFile" accept="application/xls"></file>
</form>
<input type="button" style="margin: 0 0 20 370;font-size: 15px" class="btn btn-large btn-pink save-right"
value="导入" onclick="return ajaxFileUpload();"/>
</div>
struts2 配置:
<package name="server" extends="interceptorPackge" namespace="/server">
<action name="doUploadAndInsert" class="serverBaseInfoAction" method="doUploadAndInsert" >
<result type="plainText" />
<param name="savePath">uploadTemp</param>
</action>
</package>
后端struts2 action代码:
// 上传文件所需属性
private String title;
private File uploadFile;
private String uploadFileContentType;
private String SavePath;
private String uploadFileFileName;
Log log = LogFactory.getLog(this.getClass());public String doUploadAndInsert() throws Exception {
PrintWriter out = null;
MsgBean msg = new MsgBean();
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
out = response.getWriter();
if(getUploadFile().length()>2097152){
msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail");
msg.setMsgText(getUploadFileFileName()+"上传失败,文件太大。\r\n请不要上传超过2048KB的文件");
out.write(JSON.toJSONString(msg));
out.flush();
return null;
}
//后缀名限制
String suffixName = getUploadFileFileName().split("\\.")[1];
if(!"xls".equalsIgnoreCase(suffixName)){
msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail");
msg.setMsgText(getUploadFileFileName()+"上传失败,错误的文件格式!");
out.write(JSON.toJSONString(msg));
out.flush();
return null;
} UUID uuid = UUID.randomUUID();
ServletContext servletContext = (ServletContext) ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT);
String rootPath = servletContext.getRealPath("/");
File folder = new File(rootPath + "\\" + getSavePath());
if (!folder.exists()) {
folder.mkdir();
}
FileOutputStream fileOutputStream = new FileOutputStream(rootPath + "\\" + getSavePath() + "\\" + uuid+"_"+getUploadFileFileName());
FileInputStream fileInputStream = new FileInputStream(getUploadFile());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}
fileInputStream.close();
log.info("上传文件接收成功,文件存放全路径为:" + rootPath + "/" + uuid+"_"+getUploadFileFileName()); } catch (Exception e){
msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail");
msg.setMsgText(getUploadFileFileName()+"上传失败,"+e.getMessage());
out.write(JSON.toJSONString(msg));
out.flush();
} finally{
out.close();
return null;
} }
struts2+jquery+ajax实现上传&&校验实例的更多相关文章
- jQuery.uploadify文件上传组件实例讲解
1.jquery.uploadify简介 在ASP.NET中上传的控件有很多,比如.NET自带的FileUpload,以及SWFUpload,Uploadify等等,尤其后面两个控件的用户体验比较好, ...
- 兼容ie的jquery ajax文件上传
Ajax文件上传插件很多,但兼容性各不一样,许多是对ie不兼容的,另外项目中是要求将网页内容嵌入到桌面端应用的,这样就不允许带flash的上传插件了,如:jquery uploadify...悲剧 对 ...
- Struts2 使用Jquery+ajax 文件上传
话不多说 直接上代码 前台js: var formData = new FormData(); formData.append("file1",$("#file1&quo ...
- struts2 jquery ajaxFileUpload 异步上传文件
网上搜集的,整理一下. 一.ajaxFileUpload 实现异步上传文件利用到了ajaxFileUpload.js这个文件,这是别人开发的一个jquery的插件,可以实现文件的上传并能够和strut ...
- ASP.NET 异步Web API + jQuery Ajax 文件上传代码小析
该示例中实际上应用了 jquery ajax(web client) + async web api 双异步. jquery ajax post $.ajax({ type: "POST&q ...
- 简单的jquery ajax文件上传功能
/* * 图片上传 * 注意如果不加processData:false和contentType:false会报错 */ function uploadImage(image) { var imageF ...
- Jquery Ajax异步上传
<script> $(function(){ $('#filephoto').change(function(imgFile){ console.log(imgFile) var file ...
- jQuery Ajax方式上传文件实现暂停或取消上传
未上传时要实现取消,很简单... 但如果用户点击了上传,并加载了进度信息... 2017-05-04再次改进.在上传过程中用户可以按 Esc 来取消上传(取消当前上传,或者是全部上传)... 也可以在 ...
- jQuery ajax上传文件实例
jQuery ajax上传文件实例 <form id="form" enctype="multipart/form-data"><input ...
随机推荐
- iOS开发——消息推送跳转
项目开发用集成是极光推送JPush 这里主要是消息推送过来处理对应界面跳转 同时看到两篇写的不错的相关博客分享一下: http://www.jianshu.com/ ...
- 捕获异常 winform
可以捕获winform中的异常写到文本中 <p>可以捕获winform中的异常写到文本中</p> <div class="cnblogs_code" ...
- (转)设置Win7防火墙规则 顺畅访问局域网
在Windows 7系统的电脑上搭建WAMP环境后,发现在局域网中其他电脑不能访问.有朋友告诉小强,这可能是因为当时Windows 7自带的防火墙屏蔽了80端口,只需要重新设置规则就可以了. 点击Wi ...
- (转)Flickr架构
Flickr(http://www.flickr.com/ ) 是国外一个领先的图片分享网站,现在应该在yahoo门下,感觉yahoo还是有很多好东西,奈何资本要抛弃他了.这个轮回其实挺有意思的,起先 ...
- VS2005上一个坑:关于pch 的 error C1023
昨天编译就报错: c1xx : fatal error C1023: ‘UnicodeDebug\ImEngine.pch’ : unexpected error with pch, try rebu ...
- PHP 魔术方法 __construct __destruct (一)
慢慢长寻夜,明月高空挂 __construct() - 在每次创建新对象时先调用此方法 __destruct() - 对象的所有引用都被删除或者当对象被显式销毁时执行 <?php /** * ...
- Hibernate的单向OneToMany、单向ManyToOne
单向OneToMany 一个用户有多张照片,User----->Images是一对多关系,在数据库中Images维护一个外键useid 1.在映射关系的主控方Image这边,我们什么都不做.(为 ...
- 【转】DataGridView绑定数据源的几种方式
第一种:DataSet ds=new DataSet (); this.dataGridView1.DataSource=ds.Table[0]; 第二种:DataTable dt=new DataT ...
- WeX5与阿里内测的Weex与有何纠葛?快来看HTML5开发圈那些逗逼事儿!
4月21日~23日,由infoQ主办的2016 Qcon大会北京站如期举行. HTML5开发已经成为移动开发/前端专题中无可争议的焦点,核心议题已经由前几年的是否该用HTML5转向了如何高性能.高效率 ...
- SDP协议分析
一.SDP协议介绍 SDP 完全是一种会话描述格式 ― 它不属于传输协议 ― 它只使用不同的适当的传输协议,包括会话通知协议(SAP).会话初始协议(SIP).实时流协议(RTSP).MIME 扩展协 ...