如何在剃须刀中上传文件 ASP.NET

本文关键字:文件 ASP NET 剃须刀 | 更新日期: 2023-09-27 18:11:01

我想上传文件夹图像中的文件。
我将 ASP.NET 与MVC4和剃须刀一起使用。

我的观点是这样的:

    <div class="editor-label">
         @Html.Label("Descriptif")
    </div>
    <div class="editor-field">
         <input type="file" name="fDescriptif" />
         @Html.ValidationMessageFor(model => model.fDescriptif)
    </div>
[...]
    <p>
        <input type="submit" value="Create" />
    </p>

在我的控制器中:

[HttpPost]
public ActionResult Create(formation formation)
{
    if (ModelState.IsValid)
    {
        db.formations.Add(formation);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(formation);
}

在我的模型中:

 public string fDescriptif { get; set; }

我不知道我必须做什么才能将我的文件上传到我的文件夹"image"中,并将我的文件名保存在我的数据库中。当我验证我的表单时,保存的是我的完整路径。

如何在剃须刀中上传文件 ASP.NET

在您的视图中,请确保已将enctype = "multipart/form-data"添加到form标记中,然后尝试如下操作:

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmID" }))

您可以在控制器操作中获取文件:

[HttpPost]
 public ActionResult Create(formation formation,HttpPostedFileBase file)
 {
   if (ModelState.IsValid)
   {
     // Get your File from file
   }
   return View(formation);
 }
你可以

找到很多这样的问题,即使在SO上,这个主题也给出了很多答案。

以下是其中的 2 个链接。 您应该在此链接中找到答案。 SO上还有更多其他答案。 只需谷歌一下,你就会找到它们。

https://stackoverflow.com/a/5193851/1629650

https://stackoverflow.com/a/15680783/1629650

您的表单不包含除文件以外的任何输入标记,因此在控制器操作中,您不能期望获得除上传文件之外的任何其他内容(这就是发送到服务器的全部内容(。实现此目的的一种方法是包含一个包含模型 id 的隐藏标记,这将允许您从要发布到的控制器操作中的数据存储中检索它(如果用户不应该修改模型而只是附加一个文件,请使用此选项(:

@using (Html.BeginForm("ACTION", "CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))
 @Html.TextBoxFor(m => m.File, new { @type = "file" })

CONTROLLER

[HttpPost]
    public ActionResult ACTION(ViewModels.Model taskModel)
    {
      string path = @"D:'Projects'TestApps'uploadedDocs'";
         if (taskModel.File != null) {
                taskModel.File.SaveAs(path +taskModel.TaskTitle 
                            + taskModel.File.FileName);
                 newUserProject.DocumentTitle = taskModel.TaskTitle 
                            + taskModel.File.FileName;
                  newUserProject.DocumentPath = path + taskModel.File.FileName;
                    }
}
<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);
        }
        return RedirectToAction("Index");
    }