How do I update the photo ? At the moment it is only saving in the folder, wanted to display the image

Asked

Viewed 45 times

0

        $("#btn_confirmar").click(function () {

            var form = new FormData(document.getElementById('formAlteraFoto'));

            $.ajax({
                type: 'POST',
                url: '/Usuario/AlterarFoto',
                data: form,
                processData: false,
                contentType: false,
                success: function (data) {
                    alert('Upload com sucesso!');
                },
                error: function (data, jqXHR, exception) {
                    alert('Erro ao atualizar imgem de perfil!');
                }
            });
        })
        [HttpPost]
        public ActionResult AlterarFoto()
        {
            //return RedirectToAction("Clientes");         
            
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/Uploads"), fileName);
                    file.SaveAs(path);

                }                
            }
            return RedirectToAction("EditarCliente");
        }

  • Include your view code or redenrized html from it.

  • You must return the name (or path) of the image saved in data and change with $(id ou classe da imagem).attr("src", data);

  • How so bro ? Could you show me ? Don’t manjo mt de Ajax. :(

1 answer

1


It doesn’t make sense RedirectToAction("EditarCliente"); when you do an ajax post, for the AlterarFoto(), that only uploads the file. If you inspect the return of this request by the browser itself, you will see that Response is the entire hmtl of your EditarCliente.

Also you do not make any treatment for the case of errors, for example there is already a file with this name in the destination directory or there is no permission to write in it.

You should change the AlterarFoto() for a JsonResult, below follows an example (far from representing best practices, but only an initial basis for understanding how you can solve the problem).

[HttpPost]
public JsonResult AlterarFoto()
{
    object retorno = null;                
    try
    {
        if (Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/Uploads"), fileName);
                file.SaveAs(path);

                retorno = new
                {
                    imageUrl = VirtualPathUtility.ToAbsolute("~/Content/Uploads/" + fileName),
                    sucesso = true,
                    mesagem = string.Empty
                };
            }
        }
    }
    catch (Exception e)
    {

        retorno = new
        {
            imageUrl = string.Empty,
            sucesso = false,
            mensagem = e.Message

        };
    }

    return Json(retorno, JsonRequestBehavior.AllowGet);

}

Already in your Javascript:

$("#btn_confirmar").click(function () {

    var form = new FormData(document.getElementById('formAlteraFoto'));

    $.ajax({
        type: 'POST',
        url: '/Usuario/AlterarFoto',
        data: form,
        processData: false,
        contentType: false,
        success: function (data) {
            if(data != null && data.sucesso){
                alert('Upload com sucesso!');
                //código para alterar a sua imagem na tela
                $("#seletorDoElemento").attr('src', data.imageUrl);
            }else{
                alert(data.mensagem);
            }

        },
        error: function (data, jqXHR, exception) {
            alert('Erro ao atualizar imgem de perfil!');
        }
    });
})
  • It’s just that I’m new in the area bro, so some things don’t make sense.. kkk But every tip is welcome bro ! even more good.

  • There was some doubt?

  • No bro, I’m making the changes here. Thanks again ! (:

Browser other questions tagged

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