一直以为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. Unity 5.4大赞:HTC Vive经典The lab渲染器开源

    HTC Vive提供了一个不错的免费VR demo,最近1周仔细体验了一番. 仔细看了其安装文件,竟然是Unity 5.4beta版本(通过查log,知道Valve公司用的是最新的5.4.0b11版本 ...

  2. 第四篇、微信小程序-icon组件

    属性: 效果图: test.wxml <!--成功图标--> <icon type="success" size="40"/> < ...

  3. sqlserver 大文件脚本执行

    sqlserver2008中需要执行大文件的脚本,查询分析器中打不开,需要用到sql命令,开始使用osql命令,不过提示对应sqlserver2008中的驱动找不到(具体原因未分析-空闲时在处理),使 ...

  4. dom0级事件和dom2级事件

    dom0级事件 <a href="#" id="hash" onclick="fn();fn1();"> <button ...

  5. Android - 代码片段

    转载说明 本篇文章可能已经更新,最新文章请转:http://www.sollyu.com/android-code-snippets/ 说明 此篇文章为个人日常使用所整理的一此代码片段,此篇文正将会不 ...

  6. JAVA_SE复习(basic)

    一.数据类型 1.基本数据类型 Ps:有效标识符:_.字母.$开头  之后可有数字 整型:byte 1 short 2 int 4 long 8  (字节) 取值范围:其范围是从负2 的该数据类型位数 ...

  7. mysql 不能远程连接

    不想浪费大家时间,我这文章记录了我在vagrant上架的mysql远程连接不上的问题,不过我在整理时发现这个下面这个链接,如果我一开始能找到这个我就不会绕那么多弯了.不想看我是怎么一步步调错过程的请直 ...

  8. get post

    浅谈HTTP中Get与Post的区别 2009-03-31 14:51 by hyddd, 248341 阅读, 74 评论, 收藏, 编辑 Http定义了与服务器交互的不同方法,最基本的方法有4种, ...

  9. phpcms v9 自定义分页 带下拉跳转

    <?php function new_pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array(),$setpag ...

  10. SSH-KEY服务及批量分发与管理实战

    SSH服务 一.SSH服务介绍 SSH是Secure Shell Protocol的简写,由IETF网络工作小组制定:在进行数据传输之前,SSH先对联机数据包通过加密技术进行加密处理,加密后再进行数据 ...