js实现无刷新上传

在新增数据项的时候,用ajax实现无刷新提交,但上传文件的时候,由于数据类型原因,不能将页面的<asp:FileUpload>中以字符串值的方式传到js里调用。我一共找到了两个方法予以解决,实现无刷新上传。

第一种方法:利用js的ADODB.Stream,将文件先转换成流,再通过js上传到服务器,这样有个好处就是可以上传超大文件,并且由于是数据流,可以支持断点续传、方便显示上传进度等人性化功能。唯一的缺点是要客户端浏览器需要设置安全级别,或者安装相关ActiveX控件(这个控件自己做的,加载到页面中)。

相关代码:
文件有:1个前台页面:upload.html、 1个js控制:upload.js、 1个后台处理页面:Accept.aspx(Accept.aspx.cs)
代码文件如下:
upload.html
view plaincopy to clipboardprint?
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<mce:script src="upload.js" mce_src="upload.js" language="jscript" type="text/jscript"></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div style="width:100%">
<input type="file" id="hidFilePath" />
<input type="button" id="ok" onclick="BeginUpLoadFile(‘0‘, true)" title="上传" value="UpLoad"/>
</div>
<div id="lblLeavingsTime">TIME</div>
<div id="returnInfo">Info</div>
</form>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<mce:script src="upload.js" mce_src="upload.js" language="jscript" type="text/jscript"></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div style="width:100%">
<input type="file" id="hidFilePath" />
<input type="button" id="ok" onclick="BeginUpLoadFile(‘0‘, true)" title="上传" value="UpLoad"/>
</div>
<div id="lblLeavingsTime">TIME</div>
<div id="returnInfo">Info</div>
</form>
</body>
</html>
upload.js
view plaincopy to clipboardprint?
var g_XMLHttp = null;

var g_Stream = new ActiveXObject(‘ADODB.Stream‘);

var g_SendCount = 0;
var g_TotalCount = 0;
var g_FileSize = 0;
var g_UpFileType = 0 ;
var g_BlockSize = 1024 * 100; //每段分为100K
var fileExtName = "" ; //文件后缀名
var g_PauseFlag = false;
var g_BeginTime = null;
var g_guageFlag = false ;

var Nfilename = "" ;

function Init()

{

InitTitleEvent();

BeginUpLoadFile();

}



function MoveGuage()
{
var t_Time = new Date();

var t_OddTime = Math.ceil((t_Time.getTime() - g_BeginTime.getTime()) / g_SendCount * (g_TotalCount - g_SendCount) / 1000);

var t_OddTimeString = ‘‘;

if(t_OddTime >= 3600)

{

t_OddTimeString = Math.floor(t_OddTime / 3600) + ‘时‘;

t_OddTime %= 3600;

}

if(t_OddTime >= 60)

{

t_OddTimeString += Math.floor(t_OddTime / 60) + ‘分‘;

t_OddTime %= 60;

}

document.all.lblLeavingsTime.innerText = t_OddTimeString + t_OddTime + ‘秒‘;

}


//第1个参数表示上传的类型,为命名新文件提供参考
//第2个参数表示要不要显示状态条
function BeginUpLoadFile(upFileType, guageFlag)
{
if(g_Stream == null)
{alert("您的机器不支持ADODB.Stream."); }
else
{
g_guageFlag = guageFlag ;
g_UpFileType = upFileType;
g_Stream.Type = 1;
g_Stream.Open();

var pth = document.getElementById("hidFilePath").value ;
g_Stream.LoadFromFile(pth);

var fname=pth.split(‘\\‘);
Nfilename = fname[fname.length-1] ;
fileExtName = Nfilename.split(‘.‘)[1].toLowerCase();

g_Stream.position = 0;

g_SendCount = 1;
g_FileSize = g_Stream.size ;

if (upFileType == 0) //上传图片
{
if (g_FileSize > 1024 * 1024 * 2 ) // 不能大于2M
{
document.all.returnInfo.innerText = "文件大小超过2M!" ;
g_PauseFlag = true;
return ;
}
var str = "bmp,jpg,jpeg,gif,png,icon";
if (str.search(fileExtName) == -1) //图片格式不能超出范围
{
document.all.returnInfo.innerText = "文件格式不正确,请选择bmp、jpg、jpeg、gif、png、icon格式图片!" ;
g_PauseFlag = true;
return ;
}
}


g_TotalCount = Math.ceil(g_Stream.size / g_BlockSize);
g_BeginTime = new Date();

SendData();
}



}



function SendData()

{

if(g_PauseFlag)
{
return;
}

if(g_SendCount <= g_TotalCount)
{
var t_XMLDOM = null;
var t_Root = null;
var t_Node = null;
var t_Attribute = null;
t_XMLDOM = new ActiveXObject(‘Microsoft.XMLDOM‘);
t_XMLDOM.async = false;
t_XMLDOM.resolveExternals = false;
t_Node = t_XMLDOM.createProcessingInstruction(‘xml‘,‘version="1.0"‘);
t_XMLDOM.appendChild(t_Node);
t_Root = t_XMLDOM.createElement(‘Root‘);
t_XMLDOM.appendChild(t_Root);
t_XMLDOM.documentElement.setAttribute(‘xmlns:dt‘,‘urn:schemas-microsoft-com:datatypes‘);
t_Node = t_XMLDOM.createElement(‘Data‘);
t_Node.dataType = ‘bin.base64‘;
t_Node.nodeTypedValue = g_Stream.Read(g_BlockSize);


t_Attribute = t_XMLDOM.createAttribute(‘upfiletype‘);
t_Attribute.value = g_UpFileType;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘fileindex‘);
t_Attribute.value = g_SendCount;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘totalcount‘);
t_Attribute.value = g_TotalCount;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘filesize‘);
t_Attribute.value = g_FileSize;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘blocksize‘);
t_Attribute.value = g_BlockSize;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘fileextname‘);
t_Attribute.value = fileExtName;
t_Node.setAttributeNode(t_Attribute);

t_Root.appendChild(t_Node);

g_XMLHttp = new ActiveXObject(‘Microsoft.XMLHttp‘);
g_XMLHttp.open(‘POST‘,‘AcceptFile.aspx‘,true);
g_XMLHttp.onreadystatechange = XMLHttpStateChange;
g_XMLHttp.send(t_XMLDOM);

if (g_guageFlag){ MoveGuage(); }
}

else

{
var xx = spider.BookFile.FileObj.getFileName() ;
alert(xx.value) ;

document.all.lblLeavingsTime.innerText = ‘0秒‘;

CloseWindow(document.all.cmdClose);
document.all.returnInfo.innerText = ‘文件上传完成!‘;
}

}


function XMLHttpStateChange()
{
if(g_XMLHttp.readyState == 4)
{
var rstr = g_XMLHttp.responseText ;

if(rstr == ‘OK‘)
{
g_SendCount++;
SendData();
}
else
{
document.all.returnInfo.innerText = rstr;
CloseWindow(document.all.cmdClose);
}
}

}



function CloseWindow(p_OBJ)

{

g_PauseFlag = true;

g_Stream.Close();

}
var g_XMLHttp = null;

var g_Stream = new ActiveXObject(‘ADODB.Stream‘);

var g_SendCount = 0;
var g_TotalCount = 0;
var g_FileSize = 0;
var g_UpFileType = 0 ;
var g_BlockSize = 1024 * 100; //每段分为100K
var fileExtName = "" ; //文件后缀名
var g_PauseFlag = false;
var g_BeginTime = null;
var g_guageFlag = false ;

var Nfilename = "" ;

function Init()

{

InitTitleEvent();

BeginUpLoadFile();

}

 

function MoveGuage()
{
var t_Time = new Date();

var t_OddTime = Math.ceil((t_Time.getTime() - g_BeginTime.getTime()) / g_SendCount * (g_TotalCount - g_SendCount) / 1000);

var t_OddTimeString = ‘‘;

if(t_OddTime >= 3600)

{

t_OddTimeString = Math.floor(t_OddTime / 3600) + ‘时‘;

t_OddTime %= 3600;

}

if(t_OddTime >= 60)

{

t_OddTimeString += Math.floor(t_OddTime / 60) + ‘分‘;

t_OddTime %= 60;

}

document.all.lblLeavingsTime.innerText = t_OddTimeString + t_OddTime + ‘秒‘;

}


//第1个参数表示上传的类型,为命名新文件提供参考
//第2个参数表示要不要显示状态条
function BeginUpLoadFile(upFileType, guageFlag)
{
if(g_Stream == null)
{alert("您的机器不支持ADODB.Stream."); }
else
{
g_guageFlag = guageFlag ;
g_UpFileType = upFileType;
g_Stream.Type = 1;
g_Stream.Open();

var pth = document.getElementById("hidFilePath").value ;
g_Stream.LoadFromFile(pth);

var fname=pth.split(‘\\‘);
Nfilename = fname[fname.length-1] ;
fileExtName = Nfilename.split(‘.‘)[1].toLowerCase();

g_Stream.position = 0;

g_SendCount = 1;
g_FileSize = g_Stream.size ;

if (upFileType == 0) //上传图片
{
if (g_FileSize > 1024 * 1024 * 2 ) // 不能大于2M
{
document.all.returnInfo.innerText = "文件大小超过2M!" ;
g_PauseFlag = true;
return ;
}
var str = "bmp,jpg,jpeg,gif,png,icon";
if (str.search(fileExtName) == -1) //图片格式不能超出范围
{
document.all.returnInfo.innerText = "文件格式不正确,请选择bmp、jpg、jpeg、gif、png、icon格式图片!" ;
g_PauseFlag = true;
return ;
}
}


g_TotalCount = Math.ceil(g_Stream.size / g_BlockSize);
g_BeginTime = new Date();

SendData();
}

}

 

function SendData()

{

if(g_PauseFlag)
{
return;
}

if(g_SendCount <= g_TotalCount)
{
var t_XMLDOM = null;
var t_Root = null;
var t_Node = null;
var t_Attribute = null;
t_XMLDOM = new ActiveXObject(‘Microsoft.XMLDOM‘);
t_XMLDOM.async = false;
t_XMLDOM.resolveExternals = false;
t_Node = t_XMLDOM.createProcessingInstruction(‘xml‘,‘version="1.0"‘);
t_XMLDOM.appendChild(t_Node);
t_Root = t_XMLDOM.createElement(‘Root‘);
t_XMLDOM.appendChild(t_Root);
t_XMLDOM.documentElement.setAttribute(‘xmlns:dt‘,‘urn:schemas-microsoft-com:datatypes‘);
t_Node = t_XMLDOM.createElement(‘Data‘);
t_Node.dataType = ‘bin.base64‘;
t_Node.nodeTypedValue = g_Stream.Read(g_BlockSize);


t_Attribute = t_XMLDOM.createAttribute(‘upfiletype‘);
t_Attribute.value = g_UpFileType;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘fileindex‘);
t_Attribute.value = g_SendCount;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘totalcount‘);
t_Attribute.value = g_TotalCount;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘filesize‘);
t_Attribute.value = g_FileSize;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘blocksize‘);
t_Attribute.value = g_BlockSize;
t_Node.setAttributeNode(t_Attribute);

t_Attribute = t_XMLDOM.createAttribute(‘fileextname‘);
t_Attribute.value = fileExtName;
t_Node.setAttributeNode(t_Attribute);

t_Root.appendChild(t_Node);

g_XMLHttp = new ActiveXObject(‘Microsoft.XMLHttp‘);
g_XMLHttp.open(‘POST‘,‘AcceptFile.aspx‘,true);
g_XMLHttp.onreadystatechange = XMLHttpStateChange;
g_XMLHttp.send(t_XMLDOM);

if (g_guageFlag){ MoveGuage(); }
}

else

{
var xx = spider.BookFile.FileObj.getFileName() ;
alert(xx.value) ;

document.all.lblLeavingsTime.innerText = ‘0秒‘;

CloseWindow(document.all.cmdClose);
document.all.returnInfo.innerText = ‘文件上传完成!‘;
}

}


function XMLHttpStateChange()
{
if(g_XMLHttp.readyState == 4)
{
var rstr = g_XMLHttp.responseText ;

if(rstr == ‘OK‘)
{
g_SendCount++;
SendData();
}
else
{
document.all.returnInfo.innerText = rstr;
CloseWindow(document.all.cmdClose);
}
}

}

 

function CloseWindow(p_OBJ)

{

g_PauseFlag = true;

g_Stream.Close();

}

Accept.aspx
view plaincopy to clipboardprint?
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AcceptFile.aspx.cs" Inherits="commonJS_AcceptFile" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AcceptFile.aspx.cs" Inherits="commonJS_AcceptFile" %>

Accept.aspx.cs
view plaincopy to clipboardprint?
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using spider.BookFile; //这是自己写的文件类

public partial class commonJS_AcceptFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(FileObj));


XmlDocument t_XmlDocument = new XmlDocument();

t_XmlDocument.Load(this.Request.InputStream);

XmlNode t_XmlNode = t_XmlDocument.SelectSingleNode("Root/Data");

FileObj t_FileOBJ = new FileObj();

string t_upfiletype = t_XmlNode.Attributes["upfiletype"].Value;
string t_FileIndex = t_XmlNode.Attributes["fileindex"].Value;
string t_totalcount = t_XmlNode.Attributes["totalcount"].Value;
string t_filesize = t_XmlNode.Attributes["filesize"].Value;
string t_blocksize = t_XmlNode.Attributes["blocksize"].Value;
string t_fileextname = t_XmlNode.Attributes["fileextname"].Value;
byte[] t_File = Convert.FromBase64String(t_XmlNode.FirstChild.Value);

FileObj.upfile myUpFile = new FileObj.upfile();
myUpFile.FileCount = t_totalcount;
myUpFile.FileIndex = t_FileIndex;
myUpFile.UpFileType = t_upfiletype;
myUpFile.FileSize = t_filesize;
myUpFile.BlockSize = t_blocksize;
myUpFile.ExtName = t_fileextname;

myUpFile.t_File = t_File;

FileObj.InsertFileList(myUpFile);

if (FileObj.getErrMsg == "")
{
this.Response.Write("OK");
}
else
{
this.Response.Write(FileObj.getErrMsg);
}

}
}
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using spider.BookFile; //这是自己写的文件类

public partial class commonJS_AcceptFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(FileObj));


XmlDocument t_XmlDocument = new XmlDocument();

t_XmlDocument.Load(this.Request.InputStream);

XmlNode t_XmlNode = t_XmlDocument.SelectSingleNode("Root/Data");

FileObj t_FileOBJ = new FileObj();

string t_upfiletype = t_XmlNode.Attributes["upfiletype"].Value;
string t_FileIndex = t_XmlNode.Attributes["fileindex"].Value;
string t_totalcount = t_XmlNode.Attributes["totalcount"].Value;
string t_filesize = t_XmlNode.Attributes["filesize"].Value;
string t_blocksize = t_XmlNode.Attributes["blocksize"].Value;
string t_fileextname = t_XmlNode.Attributes["fileextname"].Value;
byte[] t_File = Convert.FromBase64String(t_XmlNode.FirstChild.Value);

FileObj.upfile myUpFile = new FileObj.upfile();
myUpFile.FileCount = t_totalcount;
myUpFile.FileIndex = t_FileIndex;
myUpFile.UpFileType = t_upfiletype;
myUpFile.FileSize = t_filesize;
myUpFile.BlockSize = t_blocksize;
myUpFile.ExtName = t_fileextname;

myUpFile.t_File = t_File;

FileObj.InsertFileList(myUpFile);

if (FileObj.getErrMsg == "")
{
this.Response.Write("OK");
}
else
{
this.Response.Write(FileObj.getErrMsg);
}

}
}




第二种方法:用js动态创建form和iframe上传文件,实现无刷新。优点是代码量小,无需客户端安装控件,缺点就是上传有限制大小,下面看代码:
需要文件有:1个前台页面upload.html、 1个js函数 function upFile、 1个处理文件accept.aspx(accept.aspx.cs)
upload.html
view plaincopy to clipboardprint?
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<mce:script src="upload.js" mce_src="upload.js" language="jscript" type="text/jscript"></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div style="width:100%">
<iframe name=‘hidden_frame‘ id="hidden_frame" style=‘width:150px; height:50px; display:none;‘> </iframe>
<input type="file" id="hidFilePath" />
<input id="upBtn" type="button" class="clearBtn" style="display:none;" value="上传图片" onclick="upFile(‘hidFilePath‘);" />
</div>
</form>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<mce:script src="upload.js" mce_src="upload.js" language="jscript" type="text/jscript"></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div style="width:100%">
<iframe name=‘hidden_frame‘ id="hidden_frame" style=‘width:150px; height:50px; display:none;‘> </iframe>
<input type="file" id="hidFilePath" />
<input id="upBtn" type="button" class="clearBtn" style="display:none;" value="上传图片" onclick="upFile(‘hidFilePath‘);" />
</div>
</form>
</body>
</html>


function upFile
view plaincopy to clipboardprint?
function upFile(ob)
{
var file = document.getElementById(ob) ;
var newName = "FileName"; //设置文件保存的名字

var form=document.createElement(‘form‘);
document.body.appendChild(form);
form.encoding="multipart/form-data";
form.method = "post";
form.action= "accept.aspx?nm=" + newName;
form.target= "hidden_frame";
var pos=file.nextSibling; //记住file在旧表单中的的位置
form.appendChild(file);
form.submit();
pos.parentNode.insertBefore(file,pos);
document.body.removeChild(form);
}
function upFile(ob)
{
var file = document.getElementById(ob) ;
var newName = "FileName"; //设置文件保存的名字

var form=document.createElement(‘form‘);
document.body.appendChild(form);
form.encoding="multipart/form-data";
form.method = "post";
form.action= "accept.aspx?nm=" + newName;
form.target= "hidden_frame";
var pos=file.nextSibling; //记住file在旧表单中的的位置
form.appendChild(file);
form.submit();
pos.parentNode.insertBefore(file,pos);
document.body.removeChild(form);
}



accept.aspx
view plaincopy to clipboardprint?
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="up.aspx.cs" Inherits="Member_up" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="up.aspx.cs" Inherits="Member_up" %>

accept.aspx.cs
view plaincopy to clipboardprint?
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class Member_up : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string mz = HttpContext.Current.Request.QueryString["nm"].ToString();
string uperr = "";
HttpFileCollection files = HttpContext.Current.Request.Files;

if (files.Count>0)
{ uperr = upSingleFile(files[0], mz); }
else { uperr = "ok"; }
HttpContext.Current.Session["upInfo"] = uperr;
Response.Write(uperr);
}


//上传文件
private string upSingleFile(HttpPostedFile file, String theFileName)
{
string infos = "";
bool fileOK = false;

string fileName, fileExtension ;
fileName = System.IO.Path.GetFileName(file.FileName);
if (fileName != "")
{
if (file.ContentLength >= 1024 * 1024 * 2)
{
infos = "上传文件太大,目前仅支持2M以内的图片上传!";
}
else
{
fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
String[] allowedExtensions = { ".jpg", ".jpeg", ".gif", ".bmp", ".png", ".icon" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
break;
}
}
if (!fileOK)
{
infos = "不支持上传此类型文件!目前支持的图片格式有:jpg|jpeg|gif|bmp|png|icon";
}
else
{
file.SaveAs(System.Web.HttpContext.Current.Request.MapPath("~/books/BookPic/") + theFileName);
infos = "ok" + theFileName;
}
}
}
else
{
infos = "没有读取到文件!";
}
return infos;
}
}

js实现无刷新上传,布布扣,bubuko.com

js实现无刷新上传

上一篇:VB6之WM_COPYDATA


下一篇:Linux上非root用户jdk环境变量配置