Upload image with Vue.js + . net core 3.0

Asked

Viewed 231 times

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);
    }
}

inserir a descrição da imagem aqui

  • Cade seu controller? I can’t test it, but the right thing would be: ApiService.put('/api/manage/update', file) which is a FormData and you pass the other fields to that instance of FormData

  • @Virgilionovic made some changes and put more information.

  • I made the correction and sent an example... note

1 answer

1


Your code seems to have typo, because in sending is image and in the C# class is File, with all this I decided to do a minimal experiment that in part :

updateGeneral() {
  let fd = new FormData();
  fd.append("image", this.avatarUrl);
  fd.append("name", "name");
  fd.append("surname", "surname");
  fd.append("phoneNumber", "1836962585");
  fd.append("gender", "male");

  var myInit = {
    method: "PUT",
    mode: "cors",
    cache: "default",
    body: fd
  };
  fetch("http://localhost:62941/api/source/update-general", myInit)
    .then(c => c.json())
    .then(c => alert(c));
}

and in the code of API of :

ViewModel:

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 Image { 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)]      
  [Display(Name = "Celular")]
  public string PhoneNumber { get; set; }

  [Display(Name = "Gênero")]
  public string Gender { get; set; }
}

Controller:

[HttpPut]
[Route("update-general")]
public IActionResult UpdateGeneral([FromForm] UpdateViewModel model)
{
 if (!ModelState.IsValid)
 {
    return BadRequest(model);
 }
 return Ok(new { status = 200, message = "Status Ok" });
}

I also found a problem with the model with the wrong name. Everything leads me to believe that your project needs to verify name to name because the two problems were this.

In this example the test was done on the server simulating both the behavior of the how much of back-end

Browser other questions tagged

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