【问题标题】:Angular file uploader got blocked when uploading large file上传大文件时,角度文件上传器被阻止
【发布时间】:2021-08-21 00:01:13
【问题描述】:

我有这个适用于小文件的角度文件上传器,但对于大文件失败,并出现错误“从源 'http://localhost:4200 访问 'https://localhost:44326/api/fileUpload' 处的 XMLHttpRequest ' 已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。"

我错过了什么吗?

ts 代码

postFile(fileToUpload: File, dataType: string){
    const formData = new FormData();
    formData.append('file', fileToUpload, fileToUpload.name);
    formData.append('dataType', dataType);
    this.http.post<any>(this.rootURL + "/fileUpload", formData, {reportProgress: true, observe: 'events'})
      .subscribe(event => {
        if (event.type === HttpEventType.UploadProgress)
          this.progress = Math.round(100 * event.loaded / event.total);
        else if (event.type === HttpEventType.Response) {
          this.message = 'Upload success.';
        }
      }, error=>{
          console.log(error);
      }, () => {
        console.log("done");
      });
  }

net core API 发布代码

[HttpPost, DisableRequestSizeLimit]
    public async Task<IActionResult> UploadFile()
    {
        try
        {
            var formCollection = await ControllerContext.HttpContext.Request.ReadFormAsync();
            var file = formCollection.Files.First();

            if (file.Length > 0)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                string dataType = formCollection["DataType"].First();
                string folder = dataType.Trim().StartsWith("sample", StringComparison.OrdinalIgnoreCase) ? "Samples" : "Results";
                var fullPath = Path.Combine(pathToSave, folder, fileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
                return Ok(new { fullPath });
            }
            else
            {
                return BadRequest();
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex}");
        }
    }

【问题讨论】:

    标签: angular asp.net-core-webapi


    【解决方案1】:

    设置标头以允许在 Express 中使用 CORS 来源。 在 server.js 文件或邮件文件中添加代码。

    app.use(function(req, res, next) {
       res.header("Access-Control-Allow-Origin", "*");
       res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 2020-05-08
      • 2018-06-04
      • 2021-11-24
      • 2016-09-07
      • 2015-03-24
      • 1970-01-01
      相关资源
      最近更新 更多