首页 > 解决方案 > 尝试使用 XMLHttpRequest 上传稍大的文件会导致 POST http://.... 404 (Not Found) 和 http://... 被 CORS 策略阻止

问题描述

我得到了一个简单的 XMLHttpRequest,它只允许用户将 xml 文件从网页上传到服务器。是这样的

var formData = new FormData();
formData.append("thefile", file);
xmlhttprequest.send(formData);

我的休息服务器就是这样来接听电话的

[HttpPost, Route("api/v1/workaroundtemplates/upload")]
public async Task<IHttpActionResult> ExecuteFileUpload()
{
    IHttpActionResult res;

    try
    {
        var httpRequest = HttpContext.Current.Request;
        var requestedFiles = new List<System.IO.Stream>();

        if (httpRequest.Files.Count > 0)
        {
            HttpFileCollection files = httpRequest.Files;
            //do things
            res = Ok();
        }
        else
            res = BadRequest();

    }
    catch (Exception ex)
    {
        mLog.Error(ex, "Failed to execute action");
        res = InternalServerError(ex);
    }

    return res;
}

当我上传小文件时,这很好用。但是,当我上传稍大一些(如 50 MB)的文件时,我的浏览器控制台中出现以下错误,看起来该请求甚至从未发送到服务器。

POST http://localhost:1062/api/v1/workaroundtemplates/upload 404 (Not Found)
folder-package-list:1 Access to XMLHttpRequest at 'http://localhost:1062/api/v1/workaroundtemplates/upload' 
from origin 'http://localhost:1348' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

我尝试将此添加到我的请求标头中:

xmlhttprequest.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttprequest.setRequestHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");

这不起作用同样的错误仍然存​​在。令我困惑的是,较小的文件上传就好了。只有更大的文件才有这个问题。

Does anyone know the cause for this? I have the freedom of changing either server or client side to allow this to work.

标签: javascripthtmlrestcorsxmlhttprequest

解决方案


I figured out what is going on it has nothing to do with CORS policy. It is basically my web service in the web.config did not have the setting

<configuration>
<system.web>
    <httpRuntime maxRequestLength="1048576" />
</system.web>
</configuration>


<system.webServer>
  <security>
     <requestFiltering>
     <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

However the error message thrown on the frontend of the page is extremly confusing and not helpful at all and led me onto the wrong path


推荐阅读