最近在项目中需要上传文件文件,之前一直都是form提交的,尝试了一下AjaxForm,感觉还比较好用,写篇随笔mark下,供以后使用。

准备工作:

下载jquery-form.js

相关jar:

commons-fileupload-1.1.1.jar

commons-io-1.3.2.jar

在spring-servlet.xml进行multipartResolver配置:

<bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>

这个是必须的,否则不好用。

页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false" %>
<html>
<!--
- Author(s): xieshuang
- Date: 2016-06-20 13:46:20
- Description:
-->
<head>
<title>Title</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script src="<%=request.getContextPath()%>/common/nui/nui.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/common/nui/jquery/jquery-form.js" type="text/javascript"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/page4nui/master/projecttype/js/projecttype_import.js"></script>
<script type="text/javascript">
var contextPath="<%=request.getContextPath()%>";
</script>
</head>
<body>
<div id="test" class="nui-fit" style="padding-top:5px;min-width:300px;min-height:180px;">
<form id="fileUpload" method="post" enctype="multipart/form-data">
<div id="dataImport" style="width:100%;overflow:hidden;">
<table style="width:100%;table-layout:fixed;" class="nui-form-table" >
<tr>
<th align="right" style="width:25%" >选择文件:</th>
<td>
<input id="uploadFile" type="file" name="file" style="width:90%;"><font style="color:red;width:5%;"> *</font>
</td>
</tr>
</table>
</div>
    <div style="width:100%;padding-top:10px;" align="center">
<input style="width:60px;" iconCls="icon-ok" value="确定" type="submit" />
<span style="display:inline-block;width:25px;"></span>
<a class="nui-button" iconCls="icon-cancel" style="width:60px;" onclick="cancel">取消</a>
</div>
</form>
</div>
</body>
</html>

核心js:

var msg;
$(function(){
nui.parse();
//ajax配置
var options = {
url: contextPath+"/webapp/cfProjectType/importExcel",
beforeSubmit: showRequest, //提交前处理
success: showResponse, //处理完成
resetForm: true,
dataType: 'json'
};
$('#fileUpload').submit(function() { //注意
$(this).ajaxSubmit(options);
return false;//防止dialog 自动关闭
});
})
//执行成功回调函数
function showResponse(e) {
nui.hideMessageBox(msg);
if (e.importFlag == true) {
CloseWindow("ok");
} else {
//对错误的一些处理
}
}
//提交前的一些校验
function showRequest(formData, jqForm, options){
if(formData[0].value=="" || formData[0].value==null){
nui.alert("请选择文件");
return false;
}
var fileName = $("#uploadFile").val().split("\\").pop();
var strs = new Array(); //定义一数组
strs = fileName.split('.');
var suffix = strs [strs .length - 1];
if (suffix != 'xls' && suffix != 'xlsx') {
nui.alert("请选择excel文件!");
return false;
}
msg = nui.loading("Loading", "Please waiting");
}

java代码:

@SuppressWarnings("unchecked")
@RequestMapping("/webapp/cfProjectType/importExcel")
@ResponseBody
public Map<String, Object> importExcel(@RequestParam("file") MultipartFile[] files, HttpServletRequest request)
throws Throwable {
//long starttiem = System.currentTimeMillis();
InputStream fis;
fis = null;
File fileIn = null;
try {
for (MultipartFile myfile : files) {
if (!myfile.isEmpty()) {
String realPath = request.getSession().getServletContext().getRealPath("/export");
fileIn = new File(realPath);
//判断上传文件的保存目录是否存在
if (!fileIn.exists() && !fileIn.isDirectory()) {
//创建目录
fileIn.mkdirs(路径);
}
//将上传的文件复制到文件夹下
myfile.transferTo(new File(路径+文件名));
}
}
}

这里我之前用过另外一个方法FileUtils.copyInputStreamToFile(InputStream arg0, File arg1) 同样能将文件保存到路径下面

springMVC结合AjaxForm上传文件的更多相关文章

  1. springMVC+jsp+ajax上传文件

    工作中遇到的小问题,做个笔记 实现springMVC + jsp + ajax 上传文件 HTML <body> <form id="myform" method ...

  2. IE下AjaxForm上传文件直接提示下载的兼容性Bug

    使用AjaxForm上传文件时候,在IE下直接提示下载保存: 我的示例代码: return this.Json( new { prop1 = 5, prop2 = 10 }); 这种问题只出现在IE下 ...

  3. springMvc 使用ajax上传文件,返回获取的文件数据 附Struts2文件上传

    总结一下 springMvc使用ajax文件上传 首先说明一下,以下代码所解决的问题 :前端通过input file 标签获取文件,通过ajax与后端交互,后端获取文件,读取excel文件内容,返回e ...

  4. jquery ajaxform上传文件返回不提示信息的问题

    在使用jquery的ajaxform插件进行ajax提交表单并且上传文件的时候,返回类型datatype :json但是后台通过写出一个json对象后,在执行完以后没有进入success函数,而是直接 ...

  5. SpringMVC+jquery.uploadify 上传文件

    前言 以前用Asp.net MVC+uploadify上传文件,最近学习SpringMVC,所以就用SpringMVC+uploadify做个上传文件的demo. 刚开始用form表单的方式提交,在C ...

  6. SpringMVC使用FileUpload上传文件

    进口FileUpload和common-io的Jar包 注意:1.Struts2其它方法需要使用的:struts2过滤,将改变reqeust类型,由HttpServletRequest成为MultiP ...

  7. SpringMVC使用CommonsMultipartResolver上传文件

    DispatcherServlet并没有实现任何解析multipart请求数据的功能,它将该任务委托给了Spring中MultipartResolver策略接口的实现,通过该接口的实现类来解析mult ...

  8. SpringMVC使用StandardServletMultipartResolver上传文件

    DispatcherServlet并没有实现任何解析multipart请求数据的功能,它将该任务委托给了Spring中MultipartResolver策略接口的实现,通过该接口的实现类来解析mult ...

  9. springmvc 使用ajx上传文件 不设置form enctype

    最近在做一个小项目 碰到这个问题 解决方案如下 1.js代码如下 获取当前form 转换为formdata ajax提交到后台 var form = $("#importForm" ...

随机推荐

  1. Eclipse调用hadoop2运行MR程序(转)

    hadoop:hadoop2.2 ,windows myeclipse环境: Eclipse调用hadoop运行MR程序其实就是普通的java程序可以提交MR任务到集群执行而已.在Hadoop1中,只 ...

  2. SPSS学习系列之SPSS Text Analytics是什么?

    不多说,直接上干货! IBM® SPSS® Text Analytics 是一个IBM® SPSS® Modeler 完全集成内插式插件,它采用了先进语言技术和Natural Language Pro ...

  3. Linux-(ps,grep)

    grep命令 1.命令格式: grep [option] pattern file 2.命令功能: 用于过滤/搜索的特定字符.可使用正则表达式能多种命令配合使用,使用上十分灵活. Linux系统中gr ...

  4. vuex中怎么把‘库’中的状态对象赋值给内部对象(三种方法)

    一.通过computed的计算属性直接赋值 import store from '@/store/store' export default{ name: 'count', data(){ retur ...

  5. SQLAlchemy之SQL Expression

    SQLAlchemy是一个强大的Python SQL工具箱, 提供了包括ORM在内的各种支持. 首先使用pip安装; pip install SQLAlchemy SQL Expression Lan ...

  6. 我理解的js中预解释

    浏览器在执行代码前,先找带var和带function的地方,把带var的声明且赋予初始值undefined,把带function的声明且定义. 带var关键字预解释 让我们先看下这段代码执行的结果: ...

  7. java课件运行实践

    两数相加 源文件:Addition.java 源代码: // An addition program import javax.swing.JOptionPane;  // import class ...

  8. Android 控件:使用下拉列表框--Spinner

    ---恢复内容开始--- 一.前段代码 <Spinner android:id="@+id/spin" android:paddingTop="10px" ...

  9. Jsp&Servlet入门级项目全程实录第8讲

    惯例广告一发,对于初学真,真的很有用www.java1234.com,去试试吧! 1.添加dao public int studentAdd(Connection con,Student studen ...

  10. 键盘输入,输出int数组的函数

    public class function { public static void main(String[] args) { //输入数组数据(例如10个) int [] array = inPu ...