使用MVC应用程序上传文件

时间:2013-08-16 14:58:07

标签: asp.net-mvc

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

3 个答案:

答案 0 :(得分: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);
        }

答案 1 :(得分:0)

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

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

并做任何你想做的事情 - 读取流,保存在某个地方......

答案 2 :(得分: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的参数名称和上传控件名称应该相同。希望这有帮助