首页 > 解决方案 > 如何将上传文件的路径添加到文本框中并将其存储在数据库中?

问题描述

我有一个在事件表中注册一个新事件的表单,在这个表单中,我有一个上传按钮,用于上传文件并将其存储到名为 Uploaded_Files 的文件夹中。

一切正常,但问题是:

1)我希望报告文本框在上传文件时采用文件路径,以便我可以将该路径存储在数据库中。

2)此外,我如何上传多个文件并在其他文本框中添加它们的路径,在我的示例中为 image1 和 image2 文本框。

这是我的模型

   public class events
{
    public int Id { get; set; }
    public string title { get; set; }
    public string report { get; set; }
    public string image1 { get; set; }
    public string image2 { get; set; }
}

这是我的控制器:

     //To Retrieve list of events//

     public ActionResult Index()
    {
        var evt = _context.evt;
        if (evt==null)
        {
            return Content("No events registered in database");
        }
        return View(evt);
    }


    //Registering new event//

    public ActionResult Add_New()
    {

        return View();
    }

    [HttpPost]
    public ActionResult Save(events e)
    {
        _context.evt.Add(e);
        _context.SaveChanges();
        return RedirectToAction("Index","Events");
    }


    // Creating Upload Button //

    [HttpPost]
    public ActionResult Add_New(HttpPostedFileBase file)
    {
        try
        {
            if (file.ContentLength > 0)
            {
                string filename = Path.GetFileName(file.FileName);
                string filepath = Path.Combine(Server.MapPath("~/Uploaded_Files"), filename);
                file.SaveAs(filepath);

            }
            ViewBag.Message = "Uploaded Successfully";
            return View();
        }
        catch
        {
            ViewBag.Message = "Not uploaded";
            return View();
        }

    }

这是视图:

     @using (Html.BeginForm("Add_New", "Events", FormMethod.Post, new { enctype = "multipart/form-data" }))

     {


<div>
    @Html.TextBox("file", "", new { type = "file" })
    <input type="submit" value="submit" />
    @ViewBag.Message
</div>


  }


   @using (Html.BeginForm("Save", "events"))
  {
<div class="form-group">
    @Html.LabelFor(a => a.title)
    @Html.TextBoxFor(a => a.title, new { @class = "form-control" })
</div>
<div class="form-group">
    @Html.LabelFor(a => a.report)
    @Html.TextBoxFor(a => a.report, new { @class = "form-control" })
</div>
<div class="form-group">
    @Html.LabelFor(a => a.image1)
    @Html.TextBoxFor(a => a.image1, new { @class = "form-control"})
</div>
<div class="form-group">
    @Html.LabelFor(a => a.image2)
    @Html.TextBoxFor(a => a.image2, new { @class = "form-control" })
</div>
<button type="submit" class="btn btn-primary">Save</button>
}

我知道必须在控制器或表单和上传按钮之间的视图中合并某些内容,但我不知道如何重新编写更好的逻辑。

如果您有这方面的专业知识,请提供帮助。谢谢

标签: c#asp.net-mvcentity-framework

解决方案


我认为您正在寻找上传文件的完整路径。这受到浏览器的限制,因为它可能会引起用户的隐私问题

https://weblogs.asp.net/ashicmahtab/fileupload-control-doesn-t-give-full-path-help

如何在 C# 3.0 中获取上传文件的完整路径?


推荐阅读