在使用uploadify插件进行上传的时候涉及到可能要连同表单一起返回给后台的情况,试了很久,之前一直用"formData"属性来将序列化后的表单数据传递给后台,但怎么也获取不了,后来发现"formData"属性只能传静态参数,要传递动态参数需使用"settings"方法为"formData"属性绑定参数。主要代码如下:
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传示例</title>
<link href="${pageContext.request.contextPath }/js/uploadify/uploadify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/uploadify/swfobject.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/uploadify/jquery.uploadify.min.js"></script>
<script type="text/javascript">
$(function(){
$.fn.form2json = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [ o[this.name] ];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
}
$("#upload_file").uploadify({
"swf":"js/uploadify/uploadify.swf",
"uploader" : "upload/uploadify.action",
//"formData" : {"title":"dd","stu.name":"gg"}, //只能传静态参数,所以无法将表单的数据序列化后传递给后台
"onUploadStart" : function(file){
$("#upload_file").uploadify("settings", "formData", $('#form1').form2json());
},
"queueID" : "file_queue",
"fileObjName" : "fileName",
"buttonText": "选择文件", //按钮上的文字
"auto" : false, //是否自动开始
"multi": true, //是否支持多文件上传
"onUploadSuccess": function (file, data, response) {
$("#download_file").append("<a href='upload/download.action?fileName="+file.name+"'>"+file.name+"</a><br/>");
}
});
});
</script>
</head>
<body>
<form id="form1">
<input type="file" name="fileName" id="upload_file" />
<div id="file_queue" style="width:400px; height:200px; border:1px solid gray;"></div>
<br/>
标题:<input name="title" type="text" /><br/>
作者:<input name="stu.name" type="text" /><br/>
<p>
<a href="javascript:$('#upload_file').uploadify('upload','*');" id="btn1">开始上传</a>
<a href="javascript:$('#upload_file').uploadify('cancel','*');" id="btn2">清空队列</a>
</p>
</form>
<hr/>
<div id="download_file">
</div>
</body>
</html>
action中的属性为:
private String title;
private Student stu;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Student getStu() {
return stu;
}
public void setStu(Student stu) {
this.stu = stu;
}