0

I'm trying to upload data (image) from form to my .NET App. It saves the Path to the database correctly, but the images are not saved under "wwwroot/images". I will be grateful for your help.

        public async Task<IActionResult> Create([Bind("Id,Brand,Model,Description,Price,ImageUrl,CategoryId")] Car car)
    {
        if (ModelState.IsValid)
        {
            string webRootPath = _hostEnvironment.WebRootPath;
            var files = HttpContext.Request.Form.Files;
            if (files.Count > 0)
            {
                string fileName = Guid.NewGuid().ToString();
                var uploads = Path.Combine(webRootPath, "images");
                var extenstion = Path.GetExtension(files[0].FileName);
                var filePath = Path.Combine(uploads, fileName, extenstion);

                car.ImageUrl = "images" + "\\" + fileName + extenstion;


                using (var filesStreams = new FileStream(filePath, FileMode.Create))
                {

                    files[0].CopyTo(filesStreams);
                }
            }


            _context.Add(car);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }


        ViewData["CategoryId"] = new SelectList(_context.Categories, "Id", "Name", car.CategoryId);
        return View(car);
    } 
  • Are you sure the pictures are not saved. Have you checked with the file manager. VS sometimes does not show files. – Sadullah DOĞAN Oct 08 '20 at 20:29
  • 1
    This `car.ImageUrl = "images" + "\\" + fileName + extenstion;` is likely not saving where you think it is. https://stackoverflow.com/questions/43709657/how-to-get-root-directory-of-project-in-asp-net-core-directory-getcurrentdirect – TheGeneral Oct 08 '20 at 20:47
  • 1
    What is the value of `webRootPath` (check, don't guess)? – mjwills Oct 08 '20 at 20:59
  • Does `files[0]` have a `SaveAs` method? – mjwills Oct 08 '20 at 21:03

0 Answers0