Então estou usando este código para ver:
Isso para o modelo:
[HttpPost] public ActionResult Index(HttpPostedFileBase file) { if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); file.SaveAs(path); } return RedirectToAction("Index"); }
Funciona muito bem, a menos que o usuário adicione um arquivo que não seja uma imagem. Como posso garantir que o arquivo enviado é uma imagem. obrigado
Caso isso possa ajudar alguém, Aqui está um método estático para HttpPostedFileBase que verifica se um determinado arquivo enviado é uma imagem:
public static class HttpPostedFileBaseExtensions { public const int ImageMinimumBytes = 512; public static bool IsImage(this HttpPostedFileBase postedFile) { //------------------------------------------- // Check the image mime types //------------------------------------------- if (postedFile.ContentType.ToLower() != "image/jpg" && postedFile.ContentType.ToLower() != "image/jpeg" && postedFile.ContentType.ToLower() != "image/pjpeg" && postedFile.ContentType.ToLower() != "image/gif" && postedFile.ContentType.ToLower() != "image/x-png" && postedFile.ContentType.ToLower() != "image/png") { return false; } //------------------------------------------- // Check the image extension //------------------------------------------- if (Path.GetExtension(postedFile.FileName).ToLower() != ".jpg" && Path.GetExtension(postedFile.FileName).ToLower() != ".png" && Path.GetExtension(postedFile.FileName).ToLower() != ".gif" && Path.GetExtension(postedFile.FileName).ToLower() != ".jpeg") { return false; } //------------------------------------------- // Attempt to read the file and check the first bytes //------------------------------------------- try { if (!postedFile.InputStream.CanRead) { return false; } //------------------------------------------ //check whether the image size exceeding the limit or not //------------------------------------------ if (postedFile.ContentLength > ImageMinimumBytes) { return false; } byte[] buffer = new byte[ImageMinimumBytes]; postedFile.InputStream.Read(buffer, 0, ImageMinimumBytes); string content = System.Text.Encoding.UTF8.GetString(buffer); if (Regex.IsMatch(content, @"