如何在[FromBody] ASP.NET CORE 2& Angular 5

时间:2018-06-01 09:47:25

标签: 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>
&#13;
&#13;
&#13;

组织form.component.ts

&#13;
&#13;
// 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();
    }
  }

}
&#13;
&#13;
&#13;

单击保存按钮时

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

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

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

我发送图像和数据,我可以在我的chrome检查网络上看到: data sent to asp.net server

在服务器控制器上:

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

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

知道怎么处理这个吗?我在网上看到我们不能在表单中使用multipart / form-data ...我仍然不知道这个。请帮忙。谢谢

2 个答案:

答案 0 :(得分:0)

我相信你的Http调用有点简化了。 尝试添加Content-Type:

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

答案 1 :(得分:0)

根据我的经验,您无法像普通的Json请求一样发送文件数据。为此,您必须使用表单数据。然后您的请求将如下所示:

let formToPost = new FormData();
//stringify your normal request
let requestToPost = JSON.stringify({id:1; organizationName: ABC; legalName: DEF}); 

formToPost .append("request", requestToPost);
formToPost .append("logoFile", YOUR_IMAGE_FILE);

然后在控制器级别,您可以执行以下操作:

[HttpPost]
public async Task<YOUR_RESPON> AddTicketAsync(string request, List<IFormFile> logoFile)
{
  var request = JsonConvert.DeserializeObject<YOUR_TYPE>(request);
}

在这里,您可以直接访问您的图像文件。

希望这会有所帮助:)