Я пытаюсь отправить файл из приложения Angular 5 на мой контроллер Web API в .NET Core 2, но моя модель всегда пуста.
Если я смотрю инструменты Chrome, я вижу следующую полезную нагрузку формыв запросе:
------WebKitFormBoundaryHbjYM4AKAkl6rQFo
Content-Disposition: form-data; name="quotationId"
4
------WebKitFormBoundaryHbjYM4AKAkl6rQFo
Content-Disposition: form-data; name="quotationFile"; filename="Analisis y Oferta E3M-v1.1.pdf"
Content-Type: application/pdf
------WebKitFormBoundaryHbjYM4AKAkl6rQFo--
Угловой POST
:
quotationFileUpload(files: FileList, quotationId: number) {
if (files && files[0].size > 0) {
const formData = new FormData();
formData.append('quotationId', quotationId.toString());
formData.append('quotationFile', files[0]);
this.projectService.uploadQuotation(formData).subscribe(
response => {
this.alertService.success('Proyecto', 'Presupuesto subido correctamente.');
},
error => {
this.alertService.error('Proyecto', error.error);
}
);
}
}
Угловой метод обслуживания:
public uploadQuotation(quotation: FormData) {
return this.http.post(this.config.apiUrl + '/projects/quotations/file', quotation);
}
.NET Код:
/// <summary>
/// Upload a Quotation document.
/// </summary>
/// <param name="model"></param>
[HttpPost("quotations/file")]
[ProducesResponseType(200, Type = typeof(Quotation))]
[ProducesResponseType(400, Type = typeof(string))]
[ProducesResponseType(404, Type = typeof(string))]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public async Task<ActionResult> UploadQuotation([FromForm] QuotationUploadViewModel model)
{
try
{
var quotation = await _context.Quotations
.AsNoTracking()
.SingleOrDefaultAsync(c => c.QuotationId == System.Convert.ToInt32(model.QuotationId));
if (quotation == null)
{
return NotFound($"Presupuesto con Id {model.QuotationId} no encontrado.");
}
_context.Quotations.Update(quotation);
// Save file
var filePath = Path.Combine(_hostingEnvironment.ContentRootPath, @"Uploads", model.QuotationFile.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await model.QuotationFile.CopyToAsync(stream);
}
quotation.FileName = model.QuotationFile.FileName;
await _context.SaveChangesAsync();
return Ok(quotation);
}
catch (System.Exception ex)
{
_errorResponseMsg = $"No se pudo subir el Presupuesto {model.QuotationId}: {ex.Message}";
_logger.LogError(_errorResponseMsg);
}
return BadRequest(_errorResponseMsg);
}
QUOTATIONUPLOADVIEWMODEL
using Microsoft.AspNetCore.Http;
namespace E3m.Api.ViewModels.E3m
{
public class QuotationUploadViewModel
{
public string QuotationId { get; set; }
public IFormFile QuotationFile { get; set; }
}
}
С этим кодом свойства модели всегда равны нулю в методе web api.
Есть идеи о том, как решить эту проблему?Привет