Hirdetés

Keresés

Új hozzászólás Aktív témák

  • joysefke

    veterán

    válasz martonx #8580 üzenetére

    Nem, azt még nem próbáltam ki.

    Alapvetően én ezt az IFormFile-t akarom validálni, maga a model objektumom (Person) nem túl kritikus, annak a propertijeit az osztálydeklarációban dekoráltam [Required]-del, az a része működik és nekem egyelőre elég is.

    Dobtam a mai próbálkozásomat (elnapoltam) a kontrollert visszaállítottam a naiv, nem túl alapos kézi validálásra. Jelenleg így néz ki, csak annyi a célja az IFormFile validálásnak, hogy figyelmetlenségből ne lehessen rossz formátumot feltölteni. Tudom, hogy a fájl kiterjesztése semmit nem jelent.

    A Person egy ViewModel objektum és tárolja egy személy adatait illetve a képének a relatív útvonalát a wwwroot-hoz képest. Összesen kb 6-10 Person objektum lesz, ezek in-memory tárolódnak (és minden változás mentődik a diszkre). Ők nem userek, hanem csupán koszorúslányok-fiúk, a képük-nevük pedig a Weblapon fog virítani. Az admin egyszer konfigurálja őket a content-manager oldalon utána ezek úgy maradnak.

    A dolog nincsen túlságosan kitesztelve, de működik.

    [HttpPost] public IActionResult EditPerson(Person model, int id, IFormFile file)
    {
    // Text based informations (Person object) and IFormFile gets validated separatelly
    // The expectation is to execute EditPerson if the Person is valid, even if IFormFile is missing or invalid
    // Exceptions can only be raised bc of file IO errors. This should not break the method
    // we collect the exceptions to log details later into ModelState

    IList<Exception> exceptions = new List<Exception>();

    if (id < 0 || store.Data.People.Length <= id) ModelState.AddModelError("", "Error: route variable \"id\" has invalid value");
    if (model?.Title != "Groomsmen" && model?.Title != "Bridesmaid") ModelState.AddModelError("", "Http post request contains invalid title: must be \"Bridesmaid\" or \"Groomsmen\"");


    if (ModelState.IsValid)
    { // Person object is valid and updates the ContentStore no matter the IFormFile state
    store.Data.People[id] = model;
    store.Update(store.Data.People);
    } // IFormFile gets manually validated

    if (file != null)
    {
    string name = file.FileName;
    string ext = Path.GetExtension(file.FileName.ToLower());
    if (1024 * 1024 < file.Length) ModelState.AddModelError("", "Error: A maximum image size of 1MB allowed");
    if (ext != ".jpeg" && ext != ".jpg") ModelState.AddModelError("", "Error: JPEG file expected extension must be either *.jpeg or *.jpg");

    if (ModelState.IsValid)
    {
    // currently no renaming and no protection against malicious IFileForm-s as file upload is not available for public
    string newFileName = file.FileName;

    string newFileFullPath = Path.Combine(webRoot, imageFolder, newFileName);
    while (System.IO.File.Exists(newFileFullPath))
    {
    //gets a nice, short random file name in case of a filename conflict
    newFileName = (DateTime.Now.Ticks % 1000).ToString() + ext;
    newFileFullPath = Path.Combine(webRoot, imageFolder, newFileName);
    }
    try
    {
    using (FileStream fs = System.IO.File.Create(newFileFullPath))
    {
    file.CopyTo(fs);
    fs.Flush();
    // file path gets saved in cshtml friendly relative path
    store.Data.People[id].PictureSrc = "/" + imageFolder + "/" + newFileName;
    }
    }
    catch (Exception ex) { exceptions.Add(ex); }

    }
    if (0 < exceptions.Count)
    {
    ModelState.AddModelError("", "Error: Could not upload image");
    foreach (var ex in exceptions) ModelState.AddModelError("", ex.Message);
    }
    else store.Update(store.Data.People);
    }

    if (ModelState.IsValid) return RedirectToAction(nameof(Index));
    else
    { ViewBag.id = id;
    return View(model);
    }
    }

Új hozzászólás Aktív témák