Asp.net mvc 用MVC应用程序上传文件

Asp.net mvc 用MVC应用程序上传文件,asp.net-mvc,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, "

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

像这样拾取控制器中的文件

 [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);
        }

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

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

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

假设您的标记如下所示

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

此处,HttpPostedFileBase的参数名称和上载控件名称应相同。希望这有帮助

我现有的声明:TotalReport treport它去哪里了?所以我去了,但是文件没有上传:没有错误,但是当我检查文件夹时它是空的。忘了这是在本地主机上完成的,所以您认为这就是为什么?localhost是我的本地电脑,不是生产电脑。很抱歉,您也可以将您的模型添加为parem。明白了!这也有帮助:我试着这样做:var fileName=Path.GetFileNamefile.fileName;然而,在我的代码中,它说路径在当前内容中不存在,我如何包含它:system.path?所以我这样做了,但是,文件没有上传:没有错误,但当我检查文件夹时,它是空的。忘了这是在本地主机上完成的,所以您认为这就是为什么?localhost是我的本地电脑,不是生产电脑。我添加了保存文件的部分,请参见上文。我可以上传文件和所有内容,但无法保存!您是否已将文件数据输入到文件参数中?并检查路径是否存在。是,文件进入参数,所有。但是,当我检查文件夹时,它不在那里。我在Windows7上。
<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();
    }