gpt4 book ai didi

c# - ASP.NET MVC - 如何上传图像并将 URL 保存在数据库中

转载 作者:可可西里 更新时间:2023-11-01 13:48:03 27 4
gpt4 key购买 nike

如果有人能帮助我,我将不胜感激。我在 View 的表单中输入文件控件,当有人选择图片并单击表单上的提交按钮时,该文件必须保存在应用程序的/Pictures 文件夹中,文件路径需要保存在 SQL 数据库中字符串(例如:/Pictures/filename)。

模型类部分:

[Table("Automobil")]
public partial class Automobil
{ .....
[Required]
[StringLength(30)]
public string Fotografija{ get; set; }
......

查看(创建)文件部分:

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

....
<div class="form-group">
<div class="editor-field">
@Html.TextBoxFor(model => model.Fotografija, new { type = "file" })
@Html.ValidationMessageFor(model => model.Fotografija, "", new { @class = "text-danger" })
</div>
</div>
....

Controller 部分:

    [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "AutomobilID,Marka,Model,Godiste,Zapremina_motora,Snaga,Gorivo,Karoserija,Fotografija,Opis,Cena,Kontakt")] Automobil automobil)
{
if (ModelState.IsValid)
{
db.Automobils.Add(automobil);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(automobil);
}

我需要做什么才能将照片(Fotografija)保存在应用程序文件夹Pictures中,以及SQL base中的文件路径(如/Pictures/filename)?

预先感谢您对初学者的帮助。

最佳答案

看起来您的 Fotografija 属性是字符串类型,您要在其中保存唯一的文件名。您不想使用该字段从浏览器获取文件。让我们为此使用另一个输入字段。

@using (Html.BeginForm("Index", "Home", FormMethod.Post, 
new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="editor-field">
@Html.TextBoxFor(model => model.Model)
@Html.ValidationMessageFor(model => model.Model)
</div>
</div>
<!-- TO DO : Add other form fields also -->

<div class="form-group">
<div class="editor-field">
<input type="file" name="productImg" />
</div>
</div>
<input type="submit" />
}

现在更新您的 HttpPost 操作方法,使其具有一个类型为 HttpPostedFileBase 的参数。该参数的名称要与我们添加的输入文件字段名称相同(productImg)

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "AutomobilID,Marka,Model,Godiste,
Zapremina_motora,Snaga,Gorivo,Karoserija,Opis,Cena,Kontakt")] Automobil automobil,
HttpPostedFileBase productImg)
{
if (ModelState.IsValid)
{
if(productImg!=null)
{
var fileName = Path.GetFileName(productImg.FileName);
var directoryToSave = Server.MapPath(Url.Content("~/Pictures"));

var pathToSave = Path.Combine(directoryToSave, fileName);
productImg.SaveAs(pathToSave);
automobil.Fotografija= fileName;
}

db.Automobils.Add(automobil);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(automobil);
}

您必须删除 Fotografija 字段上的任何验证数据注释装饰(例如:[Required][MinLength] 等)。

我还强烈建议您在保存之前更新 fileName 使其成为唯一的,以避免冲突/覆盖现有文件。您可以将 DateTime 当前值添加到文件名(扩展名之前)以使其唯一

关于c# - ASP.NET MVC - 如何上传图像并将 URL 保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39182441/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com