无法将文件作为FormData从Angular上传到ASP.net

时间:2019-02-20 23:59:21

标签: asp.net angular lambda

我正在尝试将文件从我的角度代码上传到ASP.net后端。

我的Angular代码使用FormData发送对象:

public uploadFiles(files) {
  console.log(files);
  if(files.length < 1) return;

  const formData = new FormData();

  files.forEach(file => {
    console.log(file);
    formData.append(file.name, file);
  })


  this._http.postFile('/order-processing/import-orders','application/x-www-form-urlencoded' ,formData).pipe(finalize(() => {
     console.log("Finalized");
  })).subscribe((val: any) => {
      console.log('ORDER SUBMITTED', val);     
  }, error => {
     console.log(error);            
  });
}

后文件方法如下:

public postFile(path: string, contentType:string, body: FormData) : Observable<any> {

let headers = {
  'Content-Type': contentType,
  'Authorization': this.authToken
}
return this._http.post(environment.API_URL + path, body, {
  headers
});

}

我的ASP.net终结点如下:

    [HttpPost, Route("hospitality/order-processing/import-orders")]
    [RequestSizeLimit(2147483648)]
    [DisableRequestSizeLimit]
    public IActionResult UploadFile()
    {
        try
        {
            //var req = Request.Form.Files;
            var file = Request.Form.Files;
            string folderName = "Uploads";
            string webRootPath = _hostingEnvironment.WebRootPath;
            string newPath = Path.Combine(webRootPath, folderName);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }

            return Json("Upload Successful.");
        }
        catch (Exception e)
        {
            return Json("Failed:" + e);
        }
    }

如果在发送文件时检查浏览器上的“网络”选项卡,它说我的对象正在通话中,很好,但是由于某种原因,它在后端以及在我逐步执行操作时都不会被拾取。代码不存在。

略微修改此代码会出现不同的错误。现在处于状态的代码错误是“超出了表单键或值的长度限制2048”,但是有时我会遇到数组超出范围的错误,或者内容边界超出了限制错误,足以让您猛烈抨击连续面对您的键盘。

整个过程的重点是能够将excel文件上传到在AWS lambda中运行的ASP.net代码,然后将其插入RDS数据库中。我要这样做正确吗?有没有更好的方法来实现我要完成的任务?如果不是,那么我的代码出了什么问题,我不允许将文件上传到Web API?

谢谢

1 个答案:

答案 0 :(得分:0)

似乎您正在尝试设置请求的限制,但是消息指出问题出在表单键或值长度上。

尝试设置RequestFormLimits并检查是否有帮助。

[HttpPost, Route("hospitality/order-processing/import-orders")]
[RequestFormLimits(KeyLengthLimit = 8192, ValueLengthLimit = 8192)]
public IActionResult UploadFile()