ajax上传文件

今天想到了ajax上传文件的问题,不知怎样解决;于是上网搜索,在网上看到了好多文章,看到有人使用Prototype上传其实使用还是基本的方式进行
的,没有使用ajax提交文件,实现方式是使用form方式提交服务器端,然后使用ajax方式到服务器端查询服务器端文件上传的进度,然后
在客户端的进度条上显示进度,没有从更本上使用ajax方式进行上传;最终了解到其实要使用ajax上传文件要在客户端先把文件
使用javascript方式读取出来然后将读取内容通过send的方式提交到服务器端,使用这种方式可能对于客户端来说不太安全,因为脚本需要有
访问客户文件系统的权限;使用ajax方式上传文件找到了2种做法(在老外的网站上找的)一种使用的是在firefox浏览器下实现的,通过
修改浏览器设置可以访问本地文件系统,然后调用浏览中一个控件方式读取文件的内容,将文件内容和文件名称等信息组合成http协议上传文件的形势
然后通过ajax的open方法和send方法提交到服务,我觉得这种方法有些局限性(现在毕竟使用firefox的用户还是不太多),不过在firefox下能够显示已经不错了;
后来通过在 www.codeproject.com上找到通过使用ms系统中控件的方法来实现的方式,我把列出来以后说不定会用上哦;
客户端:
1、首先得到文件信息方法

function getFileParams()
{
 //Convert file path to appropriate format


 this.filePath = document.getElementById("file").value.replace(////g, "<A></A>");
 
 fso = new ActiveXObject( 'Scripting.FileSystemObject' );
 if ( !fso.FileExists(this.filePath) )
 {
  alert("Can't open file.");
  return;
 }
  
 f = fso.GetFile( this.filePath );
 this.fileSize = f.size;
 this.fileName = f.Name;
 InitStatusForm();
 InitUpload();
}

 

2、将文件的一些信息通过ajax方式先提交到服务器端



function InitUpload()

{
 document.getElementById("uploadConsole").style.display = "none";
 document.getElementById("statusConsole").style.display = "block";
 
 xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
 xmlhttp.onreadystatechange = HandleStateChange;

 var parameters = "fileSize=" + encodeURI(this.fileSize) +
 "&fileName=" + encodeURI(this.fileName)+
 "&overwriteFile=" + encodeURI(document.getElementById("overwriteFile").checked);

 xmlhttp.open("POST","<A href="http://localhost/AJAXUpload/Upload.asmx/InitUpload">http://localhost/AJAXUpload/Upload.asmx/InitUpload</A>", true);


 xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
 xmlhttp.setRequestHeader("Content-length", parameters.length);
 xmlhttp.setRequestHeader("Connection", "close");
 xmlhttp.send(parameters);
}

 

3、在服务器端有响应后再上传真正的文件内容

 


function HandleStateChange() {
 switch (xmlhttp.readyState) {
 case 4:
  response = xmlhttp.responseXML.documentElement;
  id = response.getElementsByTagName('ID')[0].firstChild.data;
  offset = esponse.getElementsByTagName('OffSet')[0].firstChild.data;
  bufferLength = response.getElementsByTagName('BufferLength')[0].firstChild.data;
  
  percentage = (offset/this.fileSize)*100;
  if (offset<this.fileSize && !this.cancelUpload)
  {
   UpdateStatusConsole(percentage, "Uploading");
   SendFilePart(offset, bufferLength);
  }
  else
  {
   SetButtonCloseState(false);
   if (this.cancelUpload)
    UpdateStatusConsole(percentage, "Canceled");
   else
    UpdateStatusConsole(percentage, "Complete");
  }
  break;
 }
}
 

 

4、上传文件内容的方法:

 


function SendFilePart(offset, length)
{
 // create SOAP XML document


 var xmlSOAP = new ActiveXObject("MSXML2.DOMDocument");
 xmlSOAP.loadXML('<?xml version="1.0" encoding="utf-8"?>'+
 '<soap:Envelope xmlns:xsi="<A href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</A>" '+
 'xmlns:xsd="<A href="http://www.w3.org/2001/XMLSchema">http://www.w3.org/2001/XMLSchema</A>" xmlns:soap="<A href="http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</A>"> '+
  '<soap:Body>'+
   '<UploadData xmlns="<A href="http://tempuri.org/">http://tempuri.org/</A>" >'+
    '<fileName>'+this.fileName+'</fileName>'+
    '<fileSize>'+this.fileSize+'</fileSize>'+
    '<file></file>'+
   '</UploadData>'+
  '</soap:Body>'+
 '</soap:Envelope>');
 
 // create a new node and set binary content


 var fileNode = xmlSOAP.selectSingleNode("//file");
 fileNode.dataType = "bin.base64";
 // open stream object and read source file


 if (adoStream.State != 1 )
 {
  adoStream.Type = 1; // 1=adTypeBinary


  adoStream.Open();
  adoStream.LoadFromFile(this.filePath);
 }
 
 adoStream.Position = offset;
 // store file content into XML node


 fileNode.nodeTypedValue = adoStream.Read(length);//adoStream.Read(-1); // -1=adReadAll


 if (adoStream.EOS)
 {
  //Close Stream


  adoStream.Close();
 }
 
 // send XML document to Web server


 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 xmlhttp.onreadystatechange = HandleStateChange;
 xmlhttp.open("POST", "<A href="http://localhost/AJAXUpload/Upload.asmx">http://localhost/AJAXUpload/Upload.asmx</A>", true);


 xmlhttp.setRequestHeader("SOAPAction", "<A href="http://tempuri.org/UploadData">http://tempuri.org/UploadData</A>");


 xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xmlhttp.send(xmlSOAP);
}

 


通过使用ADODB.Stream控件来实现文件的读取,将文件内容封装到了xml文件将xml文件上传到服务器端


以下是服务器端的代码:
[WebMethod]

 


public XmlDocument InitUpload(int fileSize, string fileName, bool overwriteFile )
{
 long offset = 0;
 string filePath = GetFilePath(fileName);
 
 if (File.Exists(filePath))
 {
  if (overwriteFile)
  {
   File.Delete(filePath);
  }
  else
  {
   using (FileStream fs = File.Open(filePath, FileMode.Append))
   {
    offset = fs.Length;
   }
  }
 }

 return GetXmlDocument(Guid.NewGuid(), string.Empty, offset,
(InitialBufferLength+offset)>fileSize?(int)(fileSize-offset):InitialBufferLength);
}

public XmlDocument UploadData(string fileName, int fileSize, byte[] file)
{
 if (fileName == null || fileName == string.Empty || file == null)
  return GetXmlDocument(Guid.NewGuid(), "Incorrect UploadData Request", 0, 0);

 string filePath = GetFilePath(fileName);

 long offset=0;
 using (FileStream fs = File.Open(filePath, FileMode.Append))
 {
  fs.Write(file, 0, file.Length);
  offset = fs.Length;
 }
 return GetXmlDocument(Guid.NewGuid(), string.Empty, offset,
(InitialBufferLength+offset)>fileSize?(int)(fileSize-offset):InitialBufferLength);
}

 

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值