c# - 如何将上传文件的路径添加到文本框中并将其存储在数据库中?
问题描述
我有一个在事件表中注册一个新事件的表单,在这个表单中,我有一个上传按钮,用于上传文件并将其存储到名为 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>
}
我知道必须在控制器或表单和上传按钮之间的视图中合并某些内容,但我不知道如何重新编写更好的逻辑。
如果您有这方面的专业知识,请提供帮助。谢谢
解决方案
我认为您正在寻找上传文件的完整路径。这受到浏览器的限制,因为它可能会引起用户的隐私问题
https://weblogs.asp.net/ashicmahtab/fileupload-control-doesn-t-give-full-path-help
推荐阅读
- html - 如何使两个元素都填充父元素(高度)?
- python - 无法从家庭 brew 安装包中的“lxml”导入名称“etree”,但在 python shell 中很好
- python - ImportError:无法导入名称“Class_name2”
- docker - 未设置因 JAVA_HOME 失败的 CloudBuild fastlane 任务,并且在您的 PATH 中找不到“java”命令
- sapui5 - 嵌入列表时的 UploadCollection instantUpload="false"
- java - 将内容上传到 AWS S3 并通过 Cloudfront 提供内容
- c++ - 如何在 C++ 中正确地从 ROS 发送数组?
- javascript - Javascript - 如何在 HTML 中显示 SessionStorage obj
- sql - 如何根据连接查询更新多行
- r - GGally::ggpairs 图不显示相关系数