c# - 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>
解决方案
我认为您没有使用:标签中的 enctype = "multipart/form-data"。例如:
<form method=post action="..."enctype = "multipart/form-data">
推荐阅读
- wordpress - 如何创建可在 Internet 访问可用时上传的离线表单?
- firebase - 如果链接未注册,Firebase 动态链接默认行为
- c++ - Visual Studio 2019 编译构建
- sql - 使用 case 语句 SQL 的单个查询中的多个计数
- python - Sklearn:如何处理数据帧
- python-3.x - 如何改变元组的形状?
- python-3.x - Python 不会打印 NOP
- sql - 仅当产品大于上个月时,我才需要 Oracle 查询以获取产品的销售额
- python - 重新运行单元格要求用户输入时,Jupyter Notebook 冻结
- multithreading - 如何检查后台作业是否已完成但在 PowerShell 中保持 Windows 窗体响应