首页 > 解决方案 > 如何在 [FromBody] ASP.NET CORE 2 和 Angular 5 中接收文件

问题描述

到目前为止,我想将文件图像从我的 Angular 5 Reactive 表单发送到我的 ASP.NET:

我的角度:

组织界面:

export interface Organization {
    id: number;
    organizationName: string;
    legalName: string;
    logoUrl: string;
    logoFile: any;
    ....
}

组织.form.html

<form [formGroup]="editForm" (ngSubmit)="save()" class="form-horizontal">
  ...
  <div class="form-group  required" [ngClass]="{'has-error': editForm.get('legalName').touched && editForm.get('legalName').hasError('required')}">
    <label class="col-sm-2" for="legalName">Legal/Trading Name</label>
    <div class="col-sm-7">
      <input class="form-control" placeholder="Legal/Trading Name" formControlName="legalName">
      <span class="help-block" *ngIf="editForm.get('legalName').touched && editForm.get('legalName').hasError('required')">Legal/Trading Name is required</span>
    </div>
  </div>
  <div class="form-group  required" [ngClass]="{'has-error': editForm.get('logoUrl').touched && editForm.get('logoUrl').hasError('required')}">
    <label class="col-sm-2" for="logoUrl">Logo</label>
    <div class="col-sm-7">
      <input type="file" accept="image/*" name="logoFile" placeholder="Logo" (change)="showPreviewImage($event)">
      <img [src]="localUrl" width="150" *ngIf="localUrl" class="imagePlaceholder">
      <input type="hidden" name="fileHidden" formControlName="logoUrl" />
      <!-- Validation Field -->

      <span class="help-block" *ngIf="editForm.get('logoUrl').touched && editForm.get('logoUrl').hasError('required')">Logo is required</span>
    </div>
  </div>

组织-form.component.ts

// i want to display a upload image so I put on localImg

showPreviewImage(event: any) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();
    var file = event.target.files[0];
    reader.readAsDataURL(file);
    reader.onload = () => {
      this.localImg= reader.result;

      this.editForm.patchValue({
        logoUrl: file.name,
        logoFile: reader.result,
      });
      this.editForm.markAsDirty();
    }
  }

}

单击保存按钮时:

save() {
  this.onSubmit.emit(this.editForm.value); 
}

接下来,我使用 HttpClient 发送到我的 asp.net core 2 服务器:

create(org: Organization) {
  return this.httpClient.post(this.baseUrl + 'organization/create', org);
}

我发送图像和数据,我可以在我的 chrome 检查网络上看到: 数据发送到 asp.net 服务器

在服务器控制器上:

[HttpPost("create")]
        public async Task<IActionResult> CreateOrganization([FromBody] OrganizationDto orgDto)
        {
            // check the same name of organization
            if (await _orgRepo.OrganizationExist(orgDto.OrganizationName))
            {
                ModelState.AddModelError("OrganizationName", "Organization Name already exists");
            }
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            var orgToCreate = _mapper.Map<Organization>(orgDto);
            var file = orgDto.LogoFile;
            if(file != null) {
                using (var stream = new FileStream(this.logosFolderPath, FileMode.Create))  
                {  
                    await file.CopyToAsync(stream);  
                    orgToCreate.LogoUrl = Path.GetFileName(file.FileName);
                    throw new Exception(orgDto.LogoUrl);
                }  
            }
            // var createdOrg = await _orgRepo.CreateOrganization(orgToCreate);
            // var orgToReturn = _mapper.Map<OrganizationDetailedDto>(createdOrg);

            // return Ok(orgToReturn);
            return Ok(orgDto);
        }

我的组织Dto:

public class OrganizationDto
    {
        [Required]
        public int Id { get; set; }
        [Required]
        public string OrganizationName { get; set; }
        [Required]
        public string LegalName { get; set; }
        [Required]
        public string LogoUrl { get; set; }
        public IFormFile LogoFile {get;set;}

但是当我调试它时,变量 orgDto 为空(未初始化或从角度接收数据)。如果我在 Angular 中将 logoFile 设置为空白,它可以工作......但是当我将文件放入其中时......它不起作用。

知道如何处理吗?我阅读了我们不能在表单中使用 multipart/form-data 的网页......我仍然对此一无所知。请帮忙。谢谢你

标签: angularfile-uploadasp.net-coreangular5

解决方案


我相信您的 Http 调用有点简化。尝试添加内容类型:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token' // if you have one
  })
};

addOrganization (org: Organization): Observable<Organization> {
  return this.httpClient.post<Organization>(this.heroesUrl, org, httpOptions)
    .pipe(
      catchError(this.handleError('addOrganization ', org))
    );
}

然后你通过订阅它来调用它,类似于以下内容:

this.addOrganization(org).subscribe(
  (data: any) => {
     console.log(data, 'returned data');
  },
  (error: any) => {
     console.error(error, 'error received');
  }
);

推荐阅读