我想從用戶文件上傳圖像並以byte []格式將其保存到數據庫。我已經嘗試了很多教程,並有搜索,但所有我試過還沒有解決我的問題。從視圖到控制器參數的圖像文件上傳在調試中返回null
問題:當我調試我的項目,將視圖中的圖像傳遞給控制器時,每次都將文件保留爲空。
這裏是我的代碼:
查看
@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);
}
這是很好的注意,我使用的視圖模型。
我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –
哦,非常抱歉沒有意識到這一點。我總是搜索這些內容,並最終自動寫入它們。 – poplebop
[so]將最流行的標籤放到搜索引擎可以找到的'