一直以为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;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;
选择文件<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实现上传&&校验实例的更多相关文章

  1. jQuery.uploadify文件上传组件实例讲解

    1.jquery.uploadify简介 在ASP.NET中上传的控件有很多,比如.NET自带的FileUpload,以及SWFUpload,Uploadify等等,尤其后面两个控件的用户体验比较好, ...

  2. 兼容ie的jquery ajax文件上传

    Ajax文件上传插件很多,但兼容性各不一样,许多是对ie不兼容的,另外项目中是要求将网页内容嵌入到桌面端应用的,这样就不允许带flash的上传插件了,如:jquery uploadify...悲剧 对 ...

  3. Struts2 使用Jquery+ajax 文件上传

    话不多说 直接上代码 前台js: var formData = new FormData(); formData.append("file1",$("#file1&quo ...

  4. struts2 jquery ajaxFileUpload 异步上传文件

    网上搜集的,整理一下. 一.ajaxFileUpload 实现异步上传文件利用到了ajaxFileUpload.js这个文件,这是别人开发的一个jquery的插件,可以实现文件的上传并能够和strut ...

  5. ASP.NET 异步Web API + jQuery Ajax 文件上传代码小析

    该示例中实际上应用了 jquery ajax(web client) + async web api 双异步. jquery ajax post $.ajax({ type: "POST&q ...

  6. 简单的jquery ajax文件上传功能

    /* * 图片上传 * 注意如果不加processData:false和contentType:false会报错 */ function uploadImage(image) { var imageF ...

  7. Jquery Ajax异步上传

    <script> $(function(){ $('#filephoto').change(function(imgFile){ console.log(imgFile) var file ...

  8. jQuery Ajax方式上传文件实现暂停或取消上传

    未上传时要实现取消,很简单... 但如果用户点击了上传,并加载了进度信息... 2017-05-04再次改进.在上传过程中用户可以按 Esc 来取消上传(取消当前上传,或者是全部上传)... 也可以在 ...

  9. jQuery ajax上传文件实例

    jQuery ajax上传文件实例 <form id="form" enctype="multipart/form-data"><input ...

随机推荐

  1. OC10_文件练习

    // // TextHander.h // OC10_文件练习 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zha ...

  2. SpringMVC接收多个对象

    问题背景: 要在一个表单里同时一次性提交多名乘客的个人信息到SpringMVC,前端HTML和SpringMVC Controller里该如何处理? 第1种方法:将Json对象序列化成Json字符串提 ...

  3. CAD输出的局部平面坐标数据配准转换到WGS84坐标系

             局部平面坐标                                             平移纠正到常用平面坐标系下的坐标            转换后的地理坐标 采用两 ...

  4. Linux 进行反编译 或者 汇编

    Linux 进行反编译 或者 汇编 一.需要的工具 1.objdump 2. 3.

  5. CCM加密学习

    这几天终于搞定了AES硬件加密工具的使用,几种简单的加密模式也都实验通过了,比较麻烦的一种是CCM模式的加密,它是CTR加密模式和CMAC认证算法的混合使用.本文先介绍CCM模式的原理与基本实现,然后 ...

  6. Qt实现桌面动态背景雪花飘落程序

            曾经收到过一份礼物,一个雪花飘落的程序,觉得效果很炫,通过前几篇的学习,我们已经掌握了贴图的一些技巧了,那么现在就可以自己实现了(当然你必须先拥有qt信号与槽的基础知识),这里先看效果 ...

  7. 实现cookie跨域访问

    需求:A系统(www.a.com)里设置一个浏览器cookie,B系统(www.b.com)需要能够访问到A设置的cookie. 通过HTML SCRIPT标签跨域写cookie: 由于html的sc ...

  8. This bison version is not supported for regeneration of the Zend/PHP parsers

    在 mac 中编译 php-src.git 报错: configure: WARNING: This bison version is not supported , excluded: ). con ...

  9. Skyline中使用AxTE3DWindowEx打开新的一个球体

    在winform窗体中拖入AxTE3DWindowEx控件. using system; using system.Collections.Generic; using System.Drawing; ...

  10. thymeleaf 模板引擎

    1.创建模板解析器 Create Template Resolver  用来加载模板 // create template resolver //创建模板解析器可以用Servlet上下文模板解析器Se ...