1

我正在尝试将文件上传添加到我的 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);
            }
4

3 回答 3

0

像这样拿起控制器中的文件

 [HttpPost]
        public ActionResult Create(HttpPostedFileBase fileUpload)
        {
            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);
        }
于 2013-08-16T15:02:01.270 回答
0

只需将已发布文件的参数添加到您的操作中:

public ActionResult Create(TotalReport treport, System.Web.HttpPostedFileBase file)

并做任何你想做的事 - 阅读流,将其保存在某处......

于 2013-08-16T15:02:53.460 回答
0

假设如果你的标记是这样的,

<input type="file" name="file" />

然后你的动作应该是这样的,

 [HttpPost]
    public ActionResult(HttpPostedFileBase file)
    {
    string filename=file.FileName;
    filename=DateTime.Now.ToString("YYYY_MM_dddd_hh_mm_ss")+filename;
    file.SaveAs("your path"+filename);
return View();
    }

这里 HttpPostedFileBase 的参数名称和上传控件名称应该相同。希望这可以帮助

于 2013-08-16T15:30:58.860 回答