public async Task <IActionResult> Create([Bind("ImageID,title,ImageFile")] ImageModel imageModel)
        {
            if (ModelState.IsValid)
            {
                //save image to wwwroot folder
                string wwwRootPath = _HostEnvironment.WebRootPath;

                string Filename = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName);

                string extension = Path.GetExtension(imageModel.ImageFile.FileName);

                //DateTime.Now ใช้เพราะ จะได้ไม่ซ้ำ
                Filename = Filename + DateTime.Now.ToString("yymmssfff") + extension;

                imageModel.ImageName = Filename;

                string path = Path.Combine(wwwRootPath + "/Images/" + Filename);

                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    await imageModel.ImageFile.CopyToAsync(fileStream);
                }

                //insert record
                _context.Add(imageModel);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(imageModel));
        }
Beispiel #2
0
        public async Task <IActionResult> Create([Bind("FirstName,LastName,Email,Password,ConfirmPassword,Dateofbirth,Phonenumber,Height,Weight,GenderId,PositionId,ImageFile")] Images images)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //save image to wwwroot folder
                    string wwwRootPath = _HostEnvironment.WebRootPath;

                    string Filename = Path.GetFileNameWithoutExtension(images.ImageFile.FileName);

                    string extension = Path.GetExtension(images.ImageFile.FileName);

                    //DateTime.Now ใช้เพราะ จะได้ไม่ซ้ำ
                    Filename = Filename + DateTime.Now.ToString("yymmssfff") + extension;

                    images.ImageName = Filename;

                    string path = Path.Combine(wwwRootPath + "/Images/" + Filename);

                    using (var fileStream = new FileStream(path, FileMode.Create))
                    {
                        await images.ImageFile.CopyToAsync(fileStream);
                    }

                    _context.Add(images);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(View(images));
        }