簡體   English   中英

如何使用ASP.NET MVC將圖像名稱上傳到數據庫?

[英]How to upload image name to database using ASP.NET MVC?

我正在嘗試在MVC中做一個電影庫,我有以下算法:

  1. 將圖像保存到特定文件夾中的服務器。 Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(archivo.FileName));
  2. 並將圖像名稱保存到數據庫。 (不是完整路徑,就像Hello.jpg一樣)。
  3. 視圖中,只需使用foreach循環鍵入<img src="/Images/@MovieGallery.Imagen"/>即可顯示它們。

(如果我的算法不好,請糾正我)

這是我的代碼:

調節器

        [HttpPost]
    public ActionResult Peliculas_Agregar(pelicula pelis)  {

        string path="";
        HttpPostedFileBase archivo = Request.Files["Imagen"]; // @name= file, capturo el name


            if (ModelState.IsValid) { // Validar si son validos los campos segun DBSET
                    try
                    {

                        if (archivo != null && archivo.ContentLength > 0) { //El nombre del archivo debe ser mayor que 0 y no debe ser nulo
                            try
                            {
                                path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(archivo.FileName));
                                archivo.SaveAs(path);

                    }
                    catch (Exception ex) {
                                ViewBag.ErrorArchivo = ex;
                            }
                        }

                        Cine.peliculas.Add(pelis);
                        Cine.SaveChanges();
                    }
                catch (Exception ex){
                        ViewBag.Error = ex;
                    }

            }
        return View(pelis);
    }

模型 (由實體框架生成)

 public int id_peli { get; set; }
    public string titulo { get; set; }
    public string director { get; set; }
    public string cast { get; set; }
    public string descripcion { get; set; }
    public Nullable<int> duracion { get; set; }
    public string categoria { get; set; }
    [DataType(DataType.Upload)]
    [Display(Name = "Cargar imagen")]
    //[Required(ErrorMessage = "Por favor carga una imagen")]
    public string imagen { get; set; } // here is where i want to save files name, not the path.

視圖

@using (Html.BeginForm("Peliculas_Agregar", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <div class="Formas">
        <div class="form-group">
            @Html.LabelFor(m => m.titulo, new { htmlAttributes = new { @for = "exampleTittle" } })
            @Html.EditorFor(m => m.titulo, new { htmlAttributes = new { @placeholder = "Título", @class = "form-control"} })
        </div>
        <div class="form-group">
            <input type="file" name="Imagen" />
        </div>
    </div>
    <input type="submit" value="Agregar Película" class="btn btn-outline-primary" />
}

我的代碼工作正常 ,但我面臨的主要問題是我不能或我不知道如何將圖像名稱保存到數據庫, 因為我沒有得到進入圖像的圖像的字符串名稱參數。 我只是得到一個名為System.Web.HttpPostedFileWrapper的字符串或類型: System.Web.HttpPostedFileWrapper

我想這是因為我使用HttpPostedFileBase將圖像保存到服務器中,但我無法編輯它並將圖像名稱保存到服務器中。 不能做兩件事。 我該怎么解決這個問題?

按照兩個喜歡的答案,我們使用視圖模型發布表單和文件。 然后,在執行數據庫操作之前,將VM字段映射到Entity的字段。

實體模型

public class Movie
{
    public string Title { get; set; }
    public string FileName { get; set; }
}

創建視圖模型以捕獲表單值

public class MovieVM
{
    public string Title { get; set; }

    [Display(Name = "Upload Image")]
    public HttpPostedFileBase Image { get; set; }
}

該操作接受MovieVM而不是實體

[HttpPost]
public ActionResult UploadMovie(MovieVM model)
{
    if (ModelState.IsValid)
    {
        // save file
        // ...

        // Map to Entity to save to db
        Movie movie = new Movie
        {
            Title = model.Title,
            FileName = model.Image.FileName
        };

        db.Movies.Add(movie);
        db.SaveChanges();

        return RedirectToAction("Success");
    }
    return View(model);
}
  1. 上傳MVC模型中包含的圖像
  2. 什么是MVC中的ViewModel?

暫無
暫無

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

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