javascript - 尝试使用 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.
解决方案
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
推荐阅读
- tomcat - 如何访问部署在 kubernetes 上的 pod tomcat 的 url
- makefile - 如何在同一个 makefile 中多次强制重建 PHONY 目标?
- r - 如何在 R fixst 中制作模型方程并选择因子交互
- amazon-web-services - Terraform aws_eks_node_group 创建错误,launch_template “不支持 - 当前不支持请求的配置”
- python - 在python中动态地将一个数组扭曲到另一个数组
- cuda - cuda fortran cufftPlanMany
- reason - 理解在reasonml文件顶部定义的模块语法
- selenium - 询问重新运行测试失败并合并(RobotFramework)
- html - CSS 在不应该更改之前的单选按钮选择时
- sharepoint-online - spfx rest api 读取图像列