Ú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
● ha kódot szúrsz be, használd a PROGRAMKÓD formázási funkciót!
- Android alkalmazások - szoftver kibeszélő topik
- Hálózati / IP kamera
- Call of Duty: Black Ops 7
- TCL LCD és LED TV-k
- iPhone topik
- Xiaomi 15T - reakció nélkül nincs egyensúly
- Autós topik látogatók beszélgetős, offolós topikja
- MasterDeeJay: Intel Optane M10: mire lehet használni?
- Sweet.tv - internetes TV
- Vigneau interaktív lokálblogja
- További aktív témák...
- Szép! HP EliteBook 855 G7 Fémházas Strapabíró Laptop 15,6" -65% AMD Ryzen 3 PRO 4450U 16/256 FHD
- Logitech G923 + állvány (PS5/PS4/PC) újszerű
- Bomba ár! HP Elitebook 850 G8 - i5-11GEN I 16GB I 256GB SSD I 15,6" FULLHD I Cam I W11 I Gari!
- Bomba ár! Lenovo ThinkPad L390 - i7-8GEN I 16GB I 256SSD I 13,3" FULL HD I HDMI I Cam I W11 I Gari!
- Bomba ár! Lenovo ThinkPad X260 - i5-6G I 8GB I 256SSD I 12,5" HD I HDMI I CAM I W11 I Gari!
- LENOVO ThinkCentre M93p (SFF)i5-4570,4GB DDR3,500GB SATA3 HDD,DVD,WIN10
- NVIDIA Quadro P400 2GB GDDR5 PCI-e videokártya
- LG UltraFine 4K - 6K és Smart Monitorok -30%
- Dell Latitude E7270,12.5",FHD,i7-6600U,8GB DDR4,256GB SSD,WIN11
- Lenovo LEGION 5 PRO Ultra 9 275HX 32GB RAM 2TB SSD RTX 5070 Ti 12GB 16" QHD+ OLED 3év Prémium GAR
Állásajánlatok
Cég: Laptopműhely Bt.
Város: Budapest
