Axios + . Net Core - Post with file

Asked

Viewed 219 times

1

I need to send the data of a form along with the Axios file and return a JSON with . netcore, I can receive the file normally in the controller but the form data cannot receive. Follows JS code

function EditDocument() {
    let url = '/Documentos/Edit/';

      var documento = {
            Ano: getAno(),
            Assunto:getAssunto(), 
            DataEnvio: getDataEnvio(),
            CaminhoArq:null,
            DataAlteracao:null,
            DataEnvio: getDataEnvio(),
            Id: getId(),
            Numeracao: getNumeracao(),
            Observacoes: getObservacoes(),
            Status:null,
            Tipo: getTipo(),
            Usuario:null,
            UsuarioId: getUsuarioId(),

        };
      var data = new FormData();
       var file = getArquivo();
      data.append('file',file);
      data.append('documento',documento);
      data.append('id',documento.Id);
      url = url  + documento.Id;
      console.log(documento)
      axios.post(url, data)
        .then(function (response) {
          let modal = document.getElementById('myModalSucess');

          console.log(response.data.Usuario.user_nicename);

          let RespostaElement = document.getElementById('Resposta');
          let RespostaText = document.createTextNode(`Documento enviado númeração: ${response.data.Numeracao}/${response.data.Ano}`);
          RespostaElement.appendChild(RespostaText);
          let UsuarioElement = document.getElementById('Usuario');
          let UsuarioText = document.createTextNode(`Usuario de envio: ${response.data.Usuario.user_nicename}`);
          UsuarioElement.appendChild(UsuarioText);
          $(modal).modal('show');


        }).catch(function (error) {
            console.log(error);
            let modal = document.getElementById('myModalError');
            let resposta = error.data;
            $("#message").append(resposta);
            $(modal).modal('show');
        });

}

If I run a console.log before making the request with Xios the document object is filled with all the data that is on screen.But in the request if I look at the Vscode debug I receive null data.

.Net

public async Task<ActionResult> Edit(int id, IFormFile file,Documento documento)
        {

          System.Console.WriteLine(documento);
           if (id != documento.Id)
           {
               return NotFound();
           }

           if (ModelState.IsValid)
           {
               try
               {

                   //verifica se foi enviado arquivo.
                   if (file != null)
                   {
                       string fileNewName = Convert.ToString(documento.Numeracao) + "_" + Convert.ToString(documento.Ano);
                       string fileNameExt;
                       try
                       {
                           fileNameExt = _arquivo.Upload(file, fileNewName);
                       }
                       catch (IOException)
                       {
                           return this.StatusCode(StatusCodes.Status203NonAuthoritative, "Arquivo já existe");
                       }
                       if (_arquivo.FileExist(fileNameExt))
                       {
                           documento.CaminhoArq = fileNameExt;
                       }
                       documento.Status = StatusDoc.Enviado;
                   }
                   //caso não enviado mantem o caminho de arquivo anterior.
                   if (file == null)
                   {
                       documento.CaminhoArq =
                          _documentoService.GetCaminhoArq(id);
                       documento.Status = StatusDoc.Aberto;
                   }



                   documento.DataAlteracao = DateTime.Now;
                   await _documentoService.UpdateAsync(documento);

               }
               catch (DbUpdateConcurrencyException)
               {
                   if (!_documentoService.Exist(documento.Id))
                   {
                       return NotFound();
                    }
                     return this.StatusCode(StatusCodes.Status500InternalServerError, "Arquivo já existe");
                 }
              documento.Usuario = _login.GetUser();
              return Json(documento); 
        }
        return this.StatusCode(StatusCodes.Status206PartialContent,"Documento enviado não valido verifique");
      }

If anyone knows what I’m doing wrong and can help me, I’m starting now and I couldn’t find anything to make it work, if you find other errors or problems in the source I’m open to criticism thank you!

1 answer

0

Whenever you post a file, you need to use "Multipart/form-data" so that the browser can break these files into pieces and send them to the server. See an explanation here.

Take an example here with Xios:

var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Important Note: Test the file reception in the backend with some REST client, such as inmsonia.

I hope I helped.

  • Thank you very much Felipe! I will study the links you passed and test

  • you can even do this without being sent as formData and without Multipart but it never gets good because the other way is Base64 and it leaves the file huge and takes away this ability of the browser to break the request into several small pieces.

  • I can send the file the problem is to receive the object in the backend it arrives empty

Browser other questions tagged

You are not signed in. Login or sign up in order to post.