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

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");
        }
    
asked by anonymous 28.06.2018 / 21:38

1 answer

1

It does not make sense to RedirectToAction("EditarCliente"); when you do a post ajax, for AlterarFoto() , which just uploads the file. If you inspect the return of this request by the same browser, you will see that the response is the integer hmtl of your EditarCliente .

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

You should change AlterarFoto() to JsonResult , below 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);

}

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!');
        }
    });
})
    
29.06.2018 / 17:34