SORU
17 HAZİRAN 2011, Cuma


Nasıl ASP.NET MVC yüklenen dosyayı doğrulamak için?

Varlık, bir nesne ve HttpPostedFileBase bir görüntü alır eylem Oluşturmak var. Görüntü varlık modele ait değil.

Varlık veritabanı nesnesi ve disk içinde dosya kurtarabilirim, ama bu iş kuralları doğrulamak için nasıl emin değilim:

  • Görüntü gereklidir
  • İçerik türü olmalı "image/png"
  • 1MB . geçmemelidir

CEVAP
17 HAZİRAN 2011, Cuma


Özel doğrulama öznitelik gitmek için bir yoldur:

public class ValidateFileAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;
        if (file == null)
        {
            return false;
        }

        if (file.ContentLength > 1 * 1024 * 1024)
        {
            return false;
        }

        try
        {
            using (var img = Image.FromStream(file.InputStream))
            {
                return img.RawFormat.Equals(ImageFormat.Png);
            }
        }
        catch { }
        return false;
    }
}

ve sonra modelinizi uygulayın:

public class MyViewModel
{
    [ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
    public HttpPostedFileBase File { get; set; }
}

Denetleyicisi bu gibi görünebilir:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // The uploaded image corresponds to our business rules => process it

        var fileName = Path.GetFileName(model.File.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
        model.File.SaveAs(path);

        return Content("Thanks for uploading", "text/plain");
    }
}

ve görünümü:

@model MyViewModel

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.LabelFor(x => x.File)
    <input type="file" name="file" />
    @Html.ValidationMessageFor(x => x.File)
    <input type="submit" value="upload" />
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • hotstrikegently

    hotstrikegen

    26 AĞUSTOS 2011
  • Attempts at least

    Attempts at

    1 Ocak 2007
  • Xcode programming tutorials

    Xcode progra

    17 EYLÜL 2006