javascript模拟简单的文件上传域
/**
* @author wsf (javascript模拟文件上传域)
*/
function createFileIpt(container, name) {
var filhtml = [];
filhtml.push("<div class='file-box'>");
filhtml.push("<input type='text' name='textfield' id='textfield' class='txt' />");
filhtml.push("<input type='button' class='btn' value='浏览...' />");
filhtml.push("<input type='file' name='"
+ name
+ "' class='file' id='"
+ name
+ "' size='28' onchange=\"document.getElementById('textfield').value=this.value\"/>");
filhtml.push("</div>");
container.append(filhtml.join(""));
appendCss();
}
/**
* 添加样式
* @returns
*/
function appendCss() {
$(".file-box").css({
"position" : "relative",
"width" : "100%",
"cursor":"pointer"
});
$(".txt").css({
"height" : "22px",
"border" : "1px solid #cdcdcd",
"width" : "180px",
"cursor":"pointer"
});
$(".btn").css({
"background-color" : "#FFF",
"border" : "1px solid #CDCDCD",
"height" : "24px",
"width" : "70px",
"cursor":"pointer"
});
var _pos = $(".txt").position();
$(".file").css({
"position" : "absolute",
"top" : "0",
"left" : _pos.left + "px",
"height" : "24px",
"filter" : "alpha(opacity:0)",
"opacity" : "0",
"width" : "250px",
"cursor":"pointer"
});
}
/**
* 创建
*/
createFileIpt($("#filecontainer"), "logo");
/**
* ajax上传文件
* @returns {Boolean}
*/
function ajaxFileUpload() {
$.ajaxFileUpload({
url : 'some.do',//用于文件上传的服务器端请求地址
secureuri : false,//一般设置为false
fileElementId : 'logo',//文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType : 'json',//返回值类型 一般设置为json
success : function(data, status)//服务器成功响应处理函数
{
alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中action中定义的成员变量
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
alert(data.message);
}
}
},
error : function(data, status, e)//服务器响应失败处理函数
{
alert(e);
}
})
return false;
}直接在页面引入js 并且在页面定义一个放上传域的dom就行了