将具有IFormFile属性的模型从Angular2上传到ASP.NET Core WebApi [英] Upload model with IFormFile propertis from Angular2 to ASP.NET Core WebApi

查看:117
本文介绍了将具有IFormFile属性的模型从Angular2上传到ASP.NET Core WebApi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发送模型,该模型的一部分是代表用户头像的一些IFormFile类型的属性.但不幸的是,我的头像属性始终为null,我看到了很多exepels如何发送单个图片元素,但是当它成为模型的一部分而不是单个元素时,我可以找到exepels如何发送

I am trying to send model which part is some IFormFile type propertis which represent user avatar. But unfortunely my avatar propertis is always null, i saw a lot of exampels how to send single picture element but i can find exampels how send it when it is part of model not a single element as it is done here for example

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

Here is my component method in which i set this props

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

}

我的公司模型在angular2端

Here my company model at angular2 side

export interface Company {
id: string,
advertiseTitle: string,
advertiseDescription: string,
city: string,
street: string,
categoryId: number,
price: number,
facebookPage: string,
instagramPage: string,
avatarImage: File

}

还有客户端的put方法

And my put methods from client side

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

在apiService中放入方法

Put method in apiService

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

我所认为的可能是JSON.stringify的原因,但它不会更改任何内容,因此请求中始终为空

Firs what i was thinking can be a reason was JSON.stringify but it don't change anything it always is empty in the request

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

Here is my backend put method(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;
  }
}

在这里还删除了[FromBody],在这种情况下请不要进行任何更改.

And here also remove [FromBody] don't change anything in this case.

推荐答案

基于此答案我设法从Angular 5向asp.net核心Web API提交了一个包含文件的表单.

Based on this answer I manage to submit a form including an file to asp.net core Web API from Angular 5.

服务器上的模型:

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

控制器动作:

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

角度模型:

export interface IWellnessPayback {
  expenseType: string;
  otherActivity: string;
  provider: string;
  requestedAmount: number;
  invoiceFile: File;
  comment: string;
}

角度服务中的方法:

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

其中this._httpHttpClient.

这篇关于将具有IFormFile属性的模型从Angular2上传到ASP.NET Core WebApi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆