我正在尝试将文件从 Angular 5 应用程序发送到 .NET Core 2 中的 Web API 控制器,但我的模型始终为空。
如果我查看 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);
}
);
}
}
Angular 服务方式:
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);
}
报价上传查看模型
using Microsoft.AspNetCore.Http;
namespace E3m.Api.ViewModels.E3m
{
public class QuotationUploadViewModel
{
public string QuotationId { get; set; }
public IFormFile QuotationFile { get; set; }
}
}
使用此代码,web api 方法中的模型属性始终为空。
关于这个问题的任何想法?问候
我发现了问题……在 Angular 中,我通过拦截器向所有带有 'Content-Type': 'application/json' 的请求添加了一个标头。删除此标题工作正常。
谢谢
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句