本文介绍了IFormFile无法获取文件(空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到一个错误
为什么它为空?请帮忙解决!!
Why is it null? Please help resolve it!!
错误行为
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".例如:
i THINK you have not used : enctype = "multipart/form-data" in tag.eg:
<form method=post action="..."enctype = "multipart/form-data">
这篇关于IFormFile无法获取文件(空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!