ajaxfileupload.js是JQuery用来完成文件传输的一个插件,其特点是异步上传文件,不需要页面的跳转,在很多场景下需要这一特点。
后台采用struts2来接收文件,因此需要导入的包有:
struts2的包:
1.commons-logging-1.0.4.jar
2.freemarker-2.3.13.jar
3.ognl-2.6.11.jar
4.struts2-core-2.16.jar
5.xwork-2.1.2.jar(高版本的struts2中此包已经整合到struts2-core-2.16.jar)
6.commons-fileupload-1.2.1.jar
7.commons-io-2.0.1.jar
8.commons-lang-2.5.jar
9.javassist-3.11.0.GA.jar
10.struts2-json-plugin-2.1.8.1.jar
还需要JQuery的包:
jquery-1.11.2.min.js
jquery-accordion-menu.js
首先在jsp页面写入文件上传域
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>文件上传</title>
</head>
<body>
上传文件:<input type="file" name="file"><br/>
<input type="button" id="upload" value="上传">
</body>
</html>
js中的代码:
$("#upload").click(function(){
$.ajaxFileUpload({
type: "POST",
url: "adminAction-upFile.action",
data:["params":data],//要传到后台的参数,没有可以不写
secureuri : false,//是否启用安全提交,默认为false
fileElementId:['file1','file2'],//文件选择框的id属性
dataType: 'content',//服务器返回的格式
async : false,
success: function(data){
alert("成功");
},
error: function (data, status, e){
alert("失败");
}
});
});
后台action中的代码:public class AdminAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private File file;
private String fileFileName;
private String fileContentType;
public String upFile(){
try{
String url = ServletActionContext.getServletContext().getRealPath("/upload");
System.out.println(url);
File myFile=new File(url);
if(!myFile.exists()){
myFile.mkdirs();
}
FileUtil.copyFile(file, new File(myFile,fileFileName));
return SUCCESS;
}catch(Exception e){
e.printStackTrace();
System.out.println("ERROR");
return ERROR;
}
}//get和set方法省略
}
struts.xml文件的配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<include file="struts-default.xml" />
<constant name="struts.devMode" value="true"/>
<package name="not_authority" extends="json-default" namespace="/">
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="adminAction-*" class="adminAction" method="{1}">
<result name="success" type="json"></result>
</action>
</package>
</struts>