简体   繁体   English

xmlHttpRequest无法使用Chrome浏览器

[英]xmlHttpRequest is not working using chrome

I have the following code for uploading file: 我有以下用于上传文件的代码:

    var formData = new FormData();
    var file = document.getElementById("file").files[0];
    formData.append("file", file);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "UploadFileServer.axd", false);
    xhr.setRequestHeader("Content-Type", "multipart/form-data");  
    xhr.setRequestHeader("Pragma", "no-cache");
    xhr.setRequestHeader("Cache-Control", "no-cache, must-revalidate");

    xhr.addEventListener('readystatechange', function(e) {
        if (this.readyState === 4) {
            if (this.status == 200 && this.response != null) {
                var clientResponse = JSON.parse(this.response);
                if (clientResponse.Success) {
                          //alert 1
                }

                else if (!clientResponse.Success) {
                          //alert 2
                }

                else {
                    //SOME ERROR!
                }
            }
        }
    });

    xhr.send(formData);

Using IE10 everything works fine. 使用IE10,一切正常。 Using Chrome, I get no files on server side: 使用Chrome,服务器端没有文件:

UploadFileServer.axd: UploadFileServer.axd:

void IHttpHandler.ProcessRequest(HttpContext ctx)
{
    OutputDebugString("Enter process req");

    HttpFileCollection uploadFile = ctx.Request.Files;
    if (uploadFile.Count > 0)
    {
         //do something

        ctx.Response.ContentType = "application/json; charset=utf-8";
        ctx.Response.Write(uploadFileResponse);
    }
}

UploadFile.Count = 0 UploadFile.Count = 0

any ideas why is it empty? 任何想法为什么它是空的?

In some browsers the uploaded file doesn't arrive at the server in the Request.Files collection when using xmlHttpRequest, but in the body of the request. 在某些浏览器中,使用xmlHttpRequest时,上载的文件不会到达Request.Files集合中的服务器,而是到达请求的正文中。

I would suggest something like: 我建议类似的东西:

if (Request.Files.AllKeys.Any())
     {
        var key = Request.Files.AllKeys.First();
        fullSizeImage = new WebImage(Request.Files[key].InputStream);
      }
      else
      {
         fullSizeImage = new WebImage(Request.InputStream);
      }

Or whatever you want to do with the image :) 或您想要对图像进行任何操作:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM