[英]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)...。一旦刪除其中一個,它就可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.