angular - 如何在 [FromBody] ASP.NET CORE 2 和 Angular 5 中接收文件

标签 angular file-upload asp.net-core angular5

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

我的 Angular :

组织界面:

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

organization.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>

organization-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 检查网络上看到: data sent to asp.net server

在服务器 Controller 上时:

[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);
        }

我的 OrganizationDto:

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;}

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

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

最佳答案

我相信您的 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');
  }
);

关于angular - 如何在 [FromBody] ASP.NET CORE 2 和 Angular 5 中接收文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50640672/

相关文章:

c# - textarea asp-for 不显示属性

Docker 容器中.Net Core 托管的 Angular 6 应用程序抛出 Npm 异常

angular - 如何在服务的 md-table 中实现 md-paginator 和 md-sort?

angular - 使用按键选择 PrimeNG 表上的行

javascript - Angular Mat AutoComplete 不显示/显示从后端返回的对象的下拉列表

php - 每个字段上传多个文件并使用 codeigniter 存储在数据库中

c# - WebAPI : Creating custom BadRequest status outside of ApiController

c# - 一个 Controller 的基于角色的授权重定向 URL

android - 文件交换 PC <--> Android 通过 USB MTP 问题

javascript - 上传前预览字体