2

我使用文件上传将文件路径插入到数据库中,并将上传的文件插入到项目目录中的文件中,我添加了我的代码,但效果不佳。

<div class="editor-field create-Bt2">
        @Html.EditorFor(model => model.Active)
        @Html.ValidationMessageFor(model => model.Active)
    </div>
    <div>
        <p class="create-Bt ">
            <input type="submit" value="Create" />
        </p>
    </div>

[HttpPost]
    public ActionResult Create(Category category)
    {
        if (ModelState.IsValid)
        {
            var fileName = "";

            var fileSavePath = "";
            var uploadedFile = Request.Files[0];
            fileName = Path.GetFileName(uploadedFile.FileName);
            fileSavePath = Server.MapPath("../../Uploads/" +
              fileName);
            uploadedFile.SaveAs(fileSavePath);


            db.Categories.Add(category);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(category);
    }
4

1 回答 1

3

在您的表格上

<form action="" method="post" enctype="multipart/form-data">

  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />

  <input type="submit" />
</form>

在你的控制器中

[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);

    // save the path to your table 
    // db.???

    db.SaveChanges();


  }

  return RedirectToAction("Index");
}
于 2012-11-21T08:59:45.177 回答