首页 > 解决方案 > 无法从表单 .NET 上传文件

问题描述

我正在尝试将数据(图像)从表单上传到我的 .NET 应用程序。它正确保存了数据库的路径,但图像未保存在“wwwroot/images”下。我会很感激你的帮助。

        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);
    } 

标签: c#asp.net.netdatabasefilestream

解决方案


推荐阅读