IFormFile变量NULL

时间:2019-11-29 04:18:26

标签: c# asp.net-mvc image model-view-controller iformfile

为什么我的thePic为null? thePic来自视图输入标签中的名称。 (请参阅控制器和视图)。它应该包含图像文件,但是给了我一个空值。行动服能够从View捕获数据,但是thePic无法捕获。请帮忙解决!

控制器:

public IActionResult Add()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public IActionResult Add(TheMobileSuit themobilesuits, 
                               IFormFile thePic)
        {       
            DbSet<TheMobileSuit> dbs = _dbContext.TheMobileSuit;

            themobilesuits.PicFile = Path.GetFileName(thePic.FileName);

            dbs.Add(themobilesuits);

            if (_dbContext.SaveChanges() == 1)
            {
                string fname = "Images/" + themobilesuits.PicFile;
                if (UploadFile(thePic, fname))
                {
                    TempData["Msg"] = "New Order Added!";
                }
                else
                {
                    return BadRequest();
                }
            }                              
            else
                TempData["Msg"] = "Error.";
            return RedirectToAction("Index");
        }

        private bool UploadFile(IFormFile ufile, string fname)
        {
            if (ufile.Length > 0)
            {
                string fullpath = Path.Combine(_env.WebRootPath, fname);
                using (var fileStream =
                           new FileStream(fullpath, FileMode.Create))
                {
                    ufile.CopyToAsync(fileStream);
                }
                return true;
            }
            return false;
        }

查看:

<div class="form-group">
            <label class="control-label col-sm-2">Photo:</label>
            <div class="col-sm-4">
                <input type="file" name="thePic"
                       class="form-control" />
            </div>
        </div>

0 个答案:

没有答案