【问题标题】:CORS error when uploading larger files上传较大文件时出现 CORS 错误
【发布时间】:2016-01-28 17:04:30
【问题描述】:

我正在使用启用了 CORS 的带有 c# web api 的 angular web 项目。

我的所有 CORS 在所有调用中都能正常工作,除非我将文件上传到异步任务。这是我所指的方法。

[HttpPost]
public async Task<HttpResponseMessage> UploadFile(){
    //code
}

我得到的错误是:

请求的资源上不存在“Access-Control-Allow-Origin”标头。

显然我什至不允许调用我的 UploadFile 方法。

在小文件上调用有效,响应中显示“Access-Control-Allow-Origin”,但在 60 mb 以上的较大文件上则没有。

我正在使用 XMLHttpRequest 进行 Web api 调用。

var xhr = new XMLHttpRequest();

        if (xhr.upload) {
            xhr.upload.filename = $scope.files[i].name;
            xhr.upload.addEventListener('progress', function (evt) {
                var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                $scope.uploadCompleteValues[this.filename] = percentComplete;
                console.log(percentComplete + '%');
                if (!$scope.$$phase) { $scope.$apply(); } 
            }, false);
        }

        xhr.onreadystatechange = function (ev) {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    // Success! Response is in xhr.responseText
                    console.log('success upload of file');



                    }
                } else {
                    // Error! Look in xhr.statusText
                    console.log('failed to upload file');
                    console.log('error : ', xhr.statusText);
                    $scope.$root.$broadcast('NOTIFY-ERROR-1btn', {
                        text: 'Artwork failed to save.  ',
                        buttons: [
                            {
                                text: 'Ok'
                            }
                        ]
                    });
                }
            }
        }

        xhr.open('POST', webapiUrl + 'artwork/UploadFile', true);
        var cookie = $cookieStore.get('authToken');
        if (cookie) {
            xhr.setRequestHeader("auth-token", cookie.token);
        } else {
            $location.path('login');
        }


        var data = new FormData();
        data.append('OrderlineId', $scope.orderline.Id);
        data.append($scope.files[i].name + 1, $scope.files[i]);
        xhr.send(data);

在通过 xhr.send 发送文件之前,跨域资源共享请求是否可能超时?

【问题讨论】:

    标签: angularjs http asp.net-web-api cors


    【解决方案1】:

    确保 web.config 中的最大允许内容长度设置得足够高,否则会出现错误。检查您的 IIS 日志以查看是否是问题所在。

          <requestFiltering>
        <requestLimits maxAllowedContentLength="4294967295" />
        <!-- bytes -->
      </requestFiltering>
    

    【讨论】:

    • 是的,就是这样。谢谢你。较大的文件不允许通过,因此在添加 CORS 标头之前就失败了。
    • 正如我所怀疑的那样。 . .
    猜你喜欢
    • 2020-10-13
    • 2022-01-23
    • 1970-01-01
    • 2020-08-07
    • 2020-08-28
    • 2016-04-14
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多