Ajax上传和ASP.NET

3
我将尝试通过ajax上传一些文本内容,稍后将对其进行解析。以下是我的Javascript代码:
 $("#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上传的文件内容?


https://dev59.com/D2PVa4cB1Zd3GeqP6ogW 是一个类似的问题。这里有关于xhr2浏览器支持的信息:http://caniuse.com/xhr2 - John Boker
是的,我的浏览器支持xhr2。而且类似的问题并不像我的问题一样... - Ricardo Pieper
1
你有看过这篇文章吗?https://dev59.com/1FvUa4cB1Zd3GeqPwb-3 - Vismari
是的,我学会了如何仅使用ajax和FileAPI来上传东西,但IE9不支持它... - Ricardo Pieper
同时也发现了为什么 HttpFileCollection 在 IE 中能够正常工作。 - Ricardo Pieper
1个回答

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");
            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接