上传照片(ASP.NET MVC 5)

问题描述 投票:0回答:1

我在上传照片时遇到了麻烦.我已经做了所有的方法,但它不工作.在银行中没有任何返回,图像也没有保存在文件夹中。

控制员:

     public ActionResult Configuracao(TerminarCadastroViewModel usuario)
            {

                try
                {
                    var vm = new UsuarioDomain();
                    if (usuario.ImageUpload != null)
                    {
                        var pic = Utilidade.UploadPhoto(usuario.ImageUpload);
                        if (!string.IsNullOrEmpty(pic))
                        {
                            vm.Imagem = string.Format("~/Imagens/{0}", pic);
                        }
                    }
                    using (UsuarioRepositorio _repUsuario = new UsuarioRepositorio())
                    {
                        var id = User.Identity.GetUserId();
                        usuario.Id = new Guid(id);
                        _repUsuario.Inserir(Mapper.Map<TerminarCadastroViewModel, UsuarioDomain>(usuario));

                    }

                    TempData["Mensagem"] = "Usuário cadastrado";
                    return View("Error");
                }
                catch (System.Exception ex)
                {
                    ViewBag.Erro = ex.Message;
                    return View(usuario);
                }
            }

UploadPhoto:

   public static string UploadPhoto(HttpPostedFileBase file)
            {
                string path = string.Empty;
                string pic = string.Empty;

                if(file != null)
                {
                    pic = Path.GetFileName(file.FileName);
                    path = Path.Combine(HttpContext.Current.Server.MapPath("~/Imagens"), pic);
                    file.SaveAs(path);
                    using ( MemoryStream ms = new MemoryStream())
                    {
                        file.InputStream.CopyTo(ms);
                        byte[] array = ms.GetBuffer();
                    }

                }
                return pic;
            }

        }
asp.net-mvc asp.net-mvc-5
1个回答
0
投票

我不确定,这个例子是否可以为你工作,但只是分享我们的一个解决方案,从js POST请求:js端上传文件(创建POST表单数据并发送)。

var formdata = new FormData();
var fileInput = document.getElementById('yourFileInputId');

for (var i = 0; i < fileInput.files.length; i++) {
    formdata.append(fileInput.files[i].name, fileInput.files[i]);
}

var xhr = new XMLHttpRequest();
xhr.open('POST', 'endpointUrl');
xhr.send(formdata);

控制器:

if (Request.Files.Count == 0)
{
  // do some thing when no files
}

for (int i = 0; i < 1; i++)
{
    HttpPostedFileBase file = Request.Files[i];
    if (file == null)
    {
        // do some thing when unable to read file
    }

    using (StreamReader r = new StreamReader(file.InputStream))
    {
        var fileContent = r.ReadToEnd();

        // process file content
     }
 }
© www.soinside.com 2019 - 2024. All rights reserved.