图像文件从视图上传到控制器参数在调试中返回 null
Image file upload from view to controller parameters returning null in debug
我正在尝试从用户文件上传图像并将其以 byte[] 格式保存到数据库中。我尝试了很多教程并进行了搜索,但我尝试过的所有方法都没有解决我的问题。
问题:当我针对将图像从视图传递到控制器的位置调试项目时,文件每次都为空。
这是我的代码:
查看
@using (Html.BeginForm("Create", "Events", new { enctype = "multipart/form-data" }, FormMethod.Post, null))
{
<div class="form-group">
<div class="col-md-10">
@Html.DisplayName("Image")
<input type="file" name="file" id="file" style="width: 100%;" />
</div>
</div>
}
控制器
[HttpPost]
public ActionResult Create(AddEventViewModel addviewmodel, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
string filename = "";
byte[] bytes;
int BytestoRead;
int numBytesRead;
if(file != null)
{
filename = Path.GetFileName(file.FileName);
bytes = new byte[file.ContentLength];
BytestoRead = (int)file.ContentLength;
numBytesRead = 0;
while(BytestoRead > 0)
{
int n = file.InputStream.Read(bytes, numBytesRead, BytestoRead);
if (n == 0) break;
numBytesRead += n;
BytestoRead -= n;
}
addviewmodel.Event_Image = bytes;
}
var e = new Event();
var ep = new EventPerformance();
UpdateEvent(e, addviewmodel);
db.Event.Add(e);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(addviewmodel);
}
请注意,我使用的是视图模型。
您的 htmlAttributes 位置错误 - 应该是:
@using (Html.BeginForm("Create", "Events", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
参见:MSDN 了解更多
仅供发现此问题并遇到相同问题的任何人,我终于找到了我的错误。我使用的是部分视图,错误地在两个视图中都有 2 @using(Html.BeginForm)...。一旦我删除其中一个,它就可以正常工作。
我正在尝试从用户文件上传图像并将其以 byte[] 格式保存到数据库中。我尝试了很多教程并进行了搜索,但我尝试过的所有方法都没有解决我的问题。
问题:当我针对将图像从视图传递到控制器的位置调试项目时,文件每次都为空。
这是我的代码:
查看
@using (Html.BeginForm("Create", "Events", new { enctype = "multipart/form-data" }, FormMethod.Post, null))
{
<div class="form-group">
<div class="col-md-10">
@Html.DisplayName("Image")
<input type="file" name="file" id="file" style="width: 100%;" />
</div>
</div>
}
控制器
[HttpPost]
public ActionResult Create(AddEventViewModel addviewmodel, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
string filename = "";
byte[] bytes;
int BytestoRead;
int numBytesRead;
if(file != null)
{
filename = Path.GetFileName(file.FileName);
bytes = new byte[file.ContentLength];
BytestoRead = (int)file.ContentLength;
numBytesRead = 0;
while(BytestoRead > 0)
{
int n = file.InputStream.Read(bytes, numBytesRead, BytestoRead);
if (n == 0) break;
numBytesRead += n;
BytestoRead -= n;
}
addviewmodel.Event_Image = bytes;
}
var e = new Event();
var ep = new EventPerformance();
UpdateEvent(e, addviewmodel);
db.Event.Add(e);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(addviewmodel);
}
请注意,我使用的是视图模型。
您的 htmlAttributes 位置错误 - 应该是:
@using (Html.BeginForm("Create", "Events", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
参见:MSDN 了解更多
仅供发现此问题并遇到相同问题的任何人,我终于找到了我的错误。我使用的是部分视图,错误地在两个视图中都有 2 @using(Html.BeginForm)...。一旦我删除其中一个,它就可以正常工作。