将具有IFormFile属性的模型从Angular2上传到ASP.NET Core WebApi

Ste*_*fan 6 asp.net-core angular

我正在尝试发送模型,该模型的一部分是代表用户头像的一些IFormFile类型属性。但不幸的是,我的化身属性始终为空,我看到很多示例文件如何发送单个图片元素,但是我可以找到示例文件如何在它作为模型的一部分而不是单个元素时发送它,例如在这里完成

这是我设置道具的组件方法

  editUser(model: Company) {
this.errors = '';
debugger;
console.log(model);
let fi = this.fileInput.nativeElement;
if (fi.files) {
  let fileToUpload = fi.files[0];
  model.avatarImage = fileToUpload;
}
model.id = this.company.id;
this.companyService.update(model)
  .subscribe(
  result => {
    if (result) {
    }
  },
  errors => this.errors = errors);
Run Code Online (Sandbox Code Playgroud)

}

这是我公司在angular2侧的模型

export interface Company {
id: string,
advertiseTitle: string,
advertiseDescription: string,
city: string,
street: string,
categoryId: number,
price: number,
facebookPage: string,
instagramPage: string,
avatarImage: File
Run Code Online (Sandbox Code Playgroud)

}

而我从客户端的put方法

    update(company: Company) {  
    return this.apiService.put(`${this.path}/${company.id}`, JSON.stringify(company));
}
Run Code Online (Sandbox Code Playgroud)

apiService中的put方法

put(path: string, body): Observable<any> {
    debugger;
    this.setBearerHeader();
    console.log('Http Post Observable: ', path, body);
    let url = `${this.baseUrl}${path}`;
    let request = new Request({
        url: url,
        headers: this.headers,
        method: RequestMethod.Put,
        body: body
    });

    return this.http.request(request)
        .catch(this.handleError)
        .map(res => res.json())
};
Run Code Online (Sandbox Code Playgroud)

首先,我在想的可能是JSON.stringify的原因,但它不会改变任何内容,因此请求中始终为空 在此处输入图片说明

这是我的后端放置方法(ASP.NET Core)

// PUT api/values/5
[HttpPut("{id}")]
public async Task<IActionResult> Put(string id, [FromBody] CompanyViewModel dto)
{
  if (!ModelState.IsValid)
  {
    return BadRequest(ModelState);
  }

  try
  {
    if (id != dto.Id)
    {
      return BadRequest();
    }

    //var entity = _mapper.Map<Company>(dto);
    //_shopDbContext.Comapnies.Update(entity);
    Company entity =  this.Get(id);
    entity.CategoryId = dto.CategoryId;
    entity.City = dto.City;
    entity.CategoryId = dto.CategoryId;
    entity.Street = dto.Street;
    entity.Price = dto.Price;
    entity.AdvertiseTitle = dto.AdvertiseTitle;
    entity.InstagramPage = dto.InstagramPage;
    entity.FacebookPage = dto.FacebookPage;
    using (var memoryStream = new MemoryStream())
    {
      await dto.AvatarImage.CopyToAsync(memoryStream);
      entity.AvatarImage = memoryStream.ToArray();
    }
    _shopDbContext.Comapnies.Update(entity);
    await _shopDbContext.SaveChangesAsync();

    return Ok(dto);
  }
  catch (Exception ex)
  {
    throw;
  }
}
Run Code Online (Sandbox Code Playgroud)

并且这里也删除了[FromBody]在这种情况下不要更改任何内容。

moi*_*eme 7

基于 这个答案,我设法从 Angular 5 提交了一个包含文件到 asp.net core Web API 的表单。

服务器上的模型:

[Required]
public string ExpenseType { get; set; }
[Required]
public string Activity { get; set; }
[Required]
public string Provider { get; set; }
[Required]
public decimal RequestedAmount { get; set; }
[Required]
public IFormFile InvoiceFile { get; set; }
public string Comment { get; set; }
Run Code Online (Sandbox Code Playgroud)

控制器动作:

[HttpPost]
public IActionResult PostPaybackRequest([FromForm] WellnessPayback payback)
{ 
    if (!ModelState.IsValid) return BadRequest(ModelState);
    // TODO
    return Ok();
}
Run Code Online (Sandbox Code Playgroud)

角度模型:

export interface IWellnessPayback {
  expenseType: string;
  otherActivity: string;
  provider: string;
  requestedAmount: number;
  invoiceFile: File;
  comment: string;
}
Run Code Online (Sandbox Code Playgroud)

角度服务中的方法:

public postPaybackRequest(payback: IWellnessPayback): Observable<boolean> {
  const formData = new FormData();
  for (const prop in payback) {
    if (!payback.hasOwnProperty(prop)) { continue; }
    formData.append(prop , payback[prop]);
  }
  return this._http.post<IOption[]>(`${this._baseUrl}/Me`, formData).pipe(map(x => true));
}
Run Code Online (Sandbox Code Playgroud)

哪里this._httpHttpClient.

  • 这是在模型中上传图像的最佳答案。除了这个之外,没有任何解决办法。谢谢... (2认同)

Mat*_*nda 0

你有两个选择:

  • 将图像作为 base64 字符串传递,如下所述:Angular 2 将图像编码为 base64。Base64 字符串可以绑定到byte[]服务器端的属性。
  • 使用多部分表单请求,如下所述:File Upload In Angular 2? 。表单部分可以使用IFormFileList<IFormFile>操作参数在服务器端绑定。