1
I’m trying to upload an image, but the image always comes as null
on my controller
This is my Viewmodel which I receive the image:
public class UpdateViewModel
{
[Required(ErrorMessage = "Nome é um campo obrigatório", AllowEmptyStrings = false)]
[StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
[Display(Name = "Nome")]
public string Name { get; set; }
[Display(Name = "Imagem")]
public IFormFile File { get; set; }
[Required(ErrorMessage = "Sobrenome é um campo obrigatório", AllowEmptyStrings = false)]
[StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
[Display(Name = "Sobrenome")]
public string Surname { get; set; }
[Required(ErrorMessage = "Telefone é um campo obrigatório", AllowEmptyStrings = false)]
// [RegularExpression(@"^\([1-9]{2}\) [2-9][0-9]{3,4}\-[0-9]{4}$", ErrorMessage = "Celular está em um formato inválido.")]
[Display(Name = "Celular")]
public string PhoneNumber { get; set; }
[Display(Name = "Gênero")]
public string Gender { get; set; }
}
And this is my Vue.js method to which I send the image:
updateGeneral: (name, surname, phoneNumber, gender, image) => {
let fd = new FormData()
fd.append('image', image)
fd.append('name', name)
fd.append('surname', surname)
fd.append('phoneNumber', phoneNumber)
fd.append('gender', gender)
return ApiService.put('/api/manage/update-general', fd )
.then(res => {
return res.data
})
.catch(err => {
return Promise.reject(err.response.data)
})
},
And as soon as I upload:
<div>
<div class="upload-img mr-4 sm:mb-0 mb-2">
<input type="file" class="hidden" ref="uploadImgInput" @change="updateCurrImg($event)" accept="image/*">
<vs-button @click="$refs.uploadImgInput.click()">{{ $t('UploadPhoto') }}</vs-button>
</div>
<p class="text-sm mt-2">{{ $t('AllowedExtensions') }} JPG {{ $t('Or') }} PNG. {{ $t('MaximumSize') }} 800kB</p>
</div>
updateCurrImg(event) {
this.avatarUrl = event.target.files[0]
},
And here’s my controller:
[HttpPut]
[Route("update-general")]
public async Task<IActionResult> UpdateGeneral([FromForm] UpdateGeneralViewModel model)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return Response(model);
}
}
Cade seu
controller
? I can’t test it, but the right thing would be:ApiService.put('/api/manage/update', file)
which is aFormData
and you pass the other fields to that instance ofFormData
– novic
@Virgilionovic made some changes and put more information.
– Matheus
I made the correction and sent an example... note
– novic