2012-07-17 80 views
3

我想通过ajax上传一些文本内容,稍后会解析。这是我的Javascript代码: Ajax上传和ASP.NET

$("#fuFile").change(function() { 
      var fileInput = document.getElementById("fuFile"); 
      var file = fileInput.files[0]; 
      var formdata = new FormData(); 
      formdata.append('file', file); 

      var xhr = new XMLHttpRequest(); 
      xhr.open("POST", 'testhandler.ashx', true); 
      xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 
      xhr.setRequestHeader("X-File-Name", file.name); 
      xhr.setRequestHeader("Content-Type", "application/octet-stream"); 
      xhr.send(formdata);    

}); 

哪里fuFile是我的文件输入,并且testhandler.ashx是服务器处理程序获取上传的文件。 (实际上我用另一个处理程序来解析文件的内容。)

但是当我尝试这样做:

HttpFileCollection fc = context.Request.Files; 

它返回任何文件。但出于某种原因在IE中工作。

但是,当我试图让输入流:

StreamReader stream = new StreamReader(context.Request.InputStream); 
    string text = stream.ReadToEnd(); 

text变量成为(HTTP头)+文件内容。

------WebKitFormBoundaryx16Mw7tnG6JeflIB\r\nContent-Disposition: form-data;name=\"file\"; filename=\"teste export.CSV\"\r\nContent-Type: application/vnd.ms-excel(..file content..) 

这是确定的,但我用这个插件:http://valums.com/ajax-upload/

和插件返回我只有文件的内容,在女巫我能得到通过的InputStream的内容,我没有收到任何HTTP头。

这是完美的,但我想做一个没有使用插件的上传脚本。只需上传并解析,返回一些结果。简单而快速

所以,我的问题是:如何获取由Ajax XHR上传的文件内容,仅在任何浏览器中获取文件内容?

+0

http://stackoverflow.com/questions/ 10475313/ajax-file-upload-with-xmlhttprequest是一个类似的问题。以下是xhr2的浏览器支持信息http://caniuse.com/xhr2 – 2012-07-17 16:58:03

+0

是的,我的浏览器支持xhr2。而类似的问题是不是类似于我的问题... – 2012-07-17 17:13:22

+1

你读过这个http://stackoverflow.com/questions/7595049/why-cant-i-upload-files-asynchronously? – Vismari 2012-10-11 19:13:20

回答

0

这对我的工作,我认为它可以帮助你

我的js函数:

$("#fuFile").click(function() { 
    var fileInput = document.getElementById("fuFile"); 
    var file = fileInput.files[0]; 
    var fd = new FormData(); 
    fd.append("files", file); 
    var xhr = new XMLHttpRequest(); 

    xhr.open("POST", 'http://localhost:63186/UploadFile.ashx'); 

    xhr.send(fd); 

}); 

我的处理程序:

string filePath = "~/Files/"; 

     //write your handler implementation here. 
     if (context.Request.Files.Count <= 0) 
     { 
      context.Response.Write("No file uploaded"); 
     } 
     else 
     { 
      for (int i = 0; i < context.Request.Files.Count; ++i) 
      { 
       HttpPostedFile file = context.Request.Files[i]; 
       var fileInfo = new FileInfo(file.FileName); 
       file.SaveAs(context.Server.MapPath(filePath + fileInfo.Name)); 
       context.Response.Write("File uploaded"); 
      } 
     }