如何将文件从angular 10上传到asp.net核心WebAPI 3.1

时间:2020-09-29 08:25:46

标签: angular asp.net-web-api .net-core file-upload

我正在尝试将文件(图像或PDF)从Angular 10应用程序上传到dotNET Core 3.1 Web API。 但是没有成功。下面是我的代码。

enter image description here

WebAPI代码

[HttpPost]
        [Route("UploadDocument")]
        public async Task<IActionResult> UploadDocument()
        {
            try
            {
                var httpRequest = HttpContext.Request.Form;
                var caseModel = new Case();

                caseModel.ApplicantName = httpRequest["ApplicantName"].ToString();
                caseModel.FatherOrSpouseName = httpRequest["FatherOrSpouseName"].ToString();
                caseModel.DateOfBirth = Convert.ToDateTime(httpRequest["DateOfBirth"].ToString());
                caseModel.EmployeeCode = httpRequest["EmployeeCode"].ToString();
                caseModel.ProcessName = httpRequest["ProcessName"].ToString();
                caseModel.LineOfBusiness = httpRequest["LineOfBusiness"].ToString();
                caseModel.DateOfBirth = Convert.ToDateTime(httpRequest["DateOfJoining"].ToString());

                await _unitOfWork.CaseRepository.CreateAsync(caseModel);

                var _allowFiles = new string[] { ".PDF", ".JPG", ".PNG", ".JPEG", ".ZIP" };

                if (httpRequest.Files.Count > 0)
                {
                    for (int i = 0; i < httpRequest.Files.Count; i++)
                    {
                        var postedFile = httpRequest.Files[i];
                        var fileName = postedFile.FileName;
                        var ext = Path.GetExtension(fileName);

                        if (_allowFiles.Contains(ext.ToUpper()))
                        {

                            string folderName = "UploadedFiles";
                            string projectRootPath = _webHostEnvironment.ContentRootPath;
                            var docSavePath = Path.Combine(projectRootPath, folderName);
                            if (!Directory.Exists(docSavePath))
                            {
                                Directory.CreateDirectory(docSavePath);
                            }

                            var docType = httpRequest["type"].ToString();
                            var docTitle = httpRequest["documentTitle"].ToString();
                            var docName = Path.GetFileNameWithoutExtension(postedFile.FileName) + "_" + Guid.NewGuid() + ext;
                            var employeeId = Convert.ToInt32(httpRequest["employeeId"]);

                            string fullPath = Path.Combine(docSavePath, docName);
                            using (var stream = new FileStream(fullPath, FileMode.Create))
                            {
                                postedFile.CopyTo(stream);
                            }
                        }
                        else
                        {
                            return BadRequest("Unsupported File Format");
                        }
                    }
                    return Ok();
                }
                return BadRequest("No File Attached");
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

角度代码(HTML代码)

 <form [formGroup]="caseForm" (ngSubmit)="saveCase()">
        <div class="row">
            <div class="col-md-3">
                Application Name
            </div>
            <div class="col-md-6">
                <input type="text" class="form-control" formControlName="ApplicantName">
            </div>
        </div>

        <div class="row mt-3">
            <div class="col-md-3">
                Select Document
            </div>
            <div class="col-md-6">
                <input type="file" class="form-control" (change)="onFileSelected($event)">
                <br>
                <span [innerHTML]="result"></span>
            </div>
        </div>

        <div class="row mt-3">
            <div class="col-md-3">

            </div>
            <div class="col-md-3">
                <button type="button" class="btn btn-block btn-secondary">Clear</button>
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-block btn-primary">Save</button>
            </div>
        </div>
    </form>

AngularCode(Component.ts)

 saveCase() {
    if (this.caseForm.valid) {
      const formData = new FormData();

      formData.append("ApplicantName", this.caseForm.value.ApplicantName);
      formData.append("file", this.selectedFile, this.selectedFile.name);

      // Display the values
      formData.forEach((value, key) => {
        console.log(key + value)
      });

      this.http.post("https://localhost:44343/api/Case/UploadDocument", formData, {
        reportProgress: true,
        observe: 'events'
      })
        .subscribe(event => {
          if (event.type === HttpEventType.UploadProgress) {
            console.log("Upload Progress: " + Math.round(event.loaded / event.total * 100) + '%')
          }
          else if (event.type === HttpEventType.Response) {
            console.log(event);
            this.toastr.success('Case', 'Case Created Successfully');
          }

          this.resetCaseForm();
        },
          err => {
            console.error(err);
          });
    }
  }

当我单击上载时。发生以下错误。

enter image description here

有人可以帮忙吗?实际上,此代码在dotNET Core 2.2中有效,但在3.1中无效。

1 个答案:

答案 0 :(得分:0)

在.net core 3中使用IFormFile接口

    [HttpPost]
    [Route("UploadDocument")]
    public async Task<IActionResult> UploadDocument([FromForm] IFormFile avatar)
    {
        using (var memoryStream = new MemoryStream())
        {
            await avatar.CopyToAsync(memoryStream);
            // Upload the file if less than 2 MB
            if (memoryStream.Length > 2097152)
            {
                ModelState.AddModelError("File", "The file is too large.");
                return BadRequest(ModelState);
            }
            return Created("","");
        }
    }