簡體   English   中英

ASP.NET MVC - 如何上傳圖像並在數據庫中保存URL

[英]ASP.NET MVC - How to upload an image and save URL in the database

如果有人能幫助我,我將不勝感激。 我在視圖中的表單中輸入文件控件,當有人選擇圖片並單擊表單上的提交按鈕時,該文件必須保存在應用程序的/ 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>
....

控制器部分:

    [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)保存在應用程序文件夾中,以及SQL庫中的文件路徑(如/ 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當前值添加到文件名(擴展名之前)以使其唯一

我在控制器中的代碼是基本代碼:

// GET: Automobili/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Automobil automobil = db.Automobils.Find(id);
        if (automobil == null)
        {
            return HttpNotFound();
        }
        return View(automobil);
    }

    // POST: Automobili/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "AutomobilID,Marka,Model,Godiste,Zapremina_motora,Snaga,Gorivo,Karoserija,Fotografija,Opis,Cena,Kontakt")] Automobil automobil)
    {
        if (ModelState.IsValid)
        {
            db.Entry(automobil).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(automobil);
    }

如何更改它以與上面的創建代碼兼容?

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM