首页 > 解决方案 > IFormFile 无法获取文件(空)

问题描述

我收到一个错误

处理请求时发生未处理的异常。NullReferenceException:对象引用未设置为对象的实例。

为什么它是空的?请帮忙解决!!

编辑:错误行是

themobilesuits.PicFile = Path.GetFileName(thePic.FileName);
[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;
}


View:

    <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>

标签: c#asp.net-mvcimagemodel-view-controller

解决方案


我认为您没有使用:标签中的 enctype = "multipart/form-data"。例如:

<form method=post action="..."enctype = "multipart/form-data">

推荐阅读