0
I’m having a problem uploading files using Angular 7 to API written in c# Asp Core 2.1. Searching the web I found several examples uploading the file only, but I need to upload the file and in the same request pass other data filled by the user.
I created a model to receive this data typed by the user:
public class MinhaViewModel{
public int UsuarioId { get; set; }
public string Descricao { get; set; }
}
And the action that should receive the data typed and the file was like this:
[HttpPost]
[Route("Publicar")]
public async Task<IActionResult> PostDocumentoUsuario([FromForm] MinhaViewModel viewModel, IFormFile file){
//save file to path and viewModel to database
}
Already in Angular I wrote the following code:
publicaArquivoUsuario(dadosUsuario):Observable<any>{
var data = new FormData();
data.append('usuarioId', dadosUsuario.usuarioId);
data.append('descricao', dadosUsuario.descricao);
data.append('file', dadosUsuario.file); //dadosUsuario.file é do tipo File
return this.http.post("urlApi", data, httpOptions);
}
Using the interface of Swagger
the request works well, but making the request by Angular always have as a return Erro 500
, where the action is not called. I have specified in the request header 'Content-Type':'multipart/form-data'
.
This code snippet
this.uploader.onBuildItemForm
... was in what part of the code? In the Component constructor?– Ricardo Alves
This is the (ng2-file-Uploader) angular plugin to upload to the file post. It would be your postArchvoUsuario, in your case you just need to add Iformfile as a property within your "Minhaviewmodel", which I believe you already solve.
– Rafael
I edited the answer, see if it helps. :)
– Rafael