Error on try to post file from Angular 6 to ASP.NET Core Web Api

I'm trying to do a POST request with multipart/form-data from an Angular 6 application to a REST service in ASP.NET Core, but I have a Error 500. I tried too many solutions, but nothing worked. I tried to execute the request on Postman and get the same problem, but I tried in other software called ARC (Advanced REST Client) and works like a charm and I don't have any idea why.

On the server-side, I getting InvalidDataException: Missing content-type boundary. In my project, I'm using swagger too

here is my code

The request in angular:

public uploadPlanilha(planilha: File, idLote: number): Observable<Array<RequisicaoComposicao>>{
    let formData = new FormData();

    formData.append('arquivo', planilha, planilha.name);
    formData.append('idLote', idLote.toString());

    let httpHeaders = new HttpHeaders();
    httpHeaders = httpHeaders.set("Content-Type", "multipart/form-data");

    return this.httpClient.post<Array<RequisicaoComposicao>>(`${this.API_URL}requisicoes/upload`, formData, {
      headers: httpHeaders
    });
  }

The controller method in Web Api

[HttpPost]
        [Route("upload")]
        [Consumes("multipart/form-data")]
        [DisableRequestSizeLimit]
        public ActionResult<List<RequisicaoComposicao>> PostPlanilhaRequisicoes([FromForm]ArquivoDto arquivoDto)
        {
            try
            {
                using (Stream arquivoPlanilha = arquivoDto.Arquivo.OpenReadStream())
                {
                    List<RequisicaoComposicao> requisicaoComposicoes = _composicaoGestor.Inserir(arquivoPlanilha, int.Parse(arquivoDto.IdLote));
                    return Ok(requisicaoComposicoes);
                }
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }

The ArquivoDto class

public class ArquivoDto
        {
            public IFormFile Arquivo { get; set; }
            public string IdLote { get; set; }
        }

Upvotes: 1

Views: 3561

Answers (2)

user10268539
user10268539

Reputation: 159

I use AngularJS + ASP.NET Core 2.1 and find the same error --> System.IO.InvalidDataException: Missing content-type boundary.

My solution is setting 'Content-Type: undefined' in http request front-end. I read somewhere at StackOverflow, you may give it a quick try if it helps.

Upvotes: 0

Anton Toshik
Anton Toshik

Reputation: 2929

Remove the [FromForm] tag you don't need it.

On this line here: formData.append('arquivo', planilha, planilha.name);

change it to formData.append('arquivo', planilha);

I never used it, therefore I don't think you need the [Consumes("multipart/form-data")] attribute ether. (unless you are using something like swagger and you want to tell it what this method is consuming then keep it)

I'd also remove this line httpHeaders = httpHeaders.set("Accept", "multipart/form-data");

Upvotes: 1

Related Questions