我正在尝试将文件上传添加到我的 asp.net mvc4,但是,由于我刚刚学习 C#,我不确定如何添加它:
这是控制器:
public ActionResult Create()
{
ViewBag.c_id = new SelectList(db.Cities.OrderBy(o => o.name), "c_id", "name");
ViewBag.m_id = new SelectList(db.Schools, "m_id", "name");
return View();
}
//
// POST: /Create
[HttpPost]
public ActionResult Create(TotalReport treport)
{
if (ModelState.IsValid)
{
treport.created = DateTime.Now;
db.TotalReports.Add(treport);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.c_id = new SelectList(db.Cities.OrderBy(o => o.name), "c_id", "name");
ViewBag.m_id = new SelectList(db.Schools, "m_id", "name");
return View(treport);
}
视图在这里:
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<div class="mycss">
<input type="file" name="file" />
</div>
</fieldset>
好的,这是保存文件的部分:
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = System.IO.Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = System.IO.Path.Combine(Server.MapPath("~/myfolder"), fileName);
file.SaveAs(path);
}