gpt4 book ai didi

c# - 如何将图像保存在数据库中并将其显示到 MVC 4 中的 View 中?

转载 作者:太空狗 更新时间:2023-10-29 22:26:37 25 4
gpt4 key购买 nike

我有如下表格:

CREATE TABLE [dbo].[tblA]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[fname] NVARCHAR(50) NULL,
[lname] NVARCHAR(50) NULL,
[imageUrl] NVARCHAR(50) NULL
)

我想使用文件上传来上传文件。如何将图像保存到数据库中并显示到 View 中?

最佳答案

  1. 在解决方案资源管理器中创建一个“图像”文件夹
  2. 创建一个 ADO.NET 实体数据模型(在这个例子中是“Database1Entities”)
  3. 首页 Controller :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    namespace test2.Controllers
    {
    public class HomeController : Controller
    {
    public ActionResult Index()
    {
    return View();
    }

    public ActionResult FileUpload(HttpPostedFileBase file)
    {

    if (file != null)
    {
    Database1Entities db = new Database1Entities();
    string ImageName = System.IO.Path.GetFileName(file.FileName);
    string physicalPath =Server.MapPath("~/images/"+ ImageName);

    // save image in folder
    file.SaveAs(physicalPath);

    //save new record in database
    tblA newRecord = new tblA();
    newRecord.fname = Request.Form["fname"];
    newRecord.lname = Request.Form["lname"];
    newRecord.imageUrl = ImageName;
    db.tblAs.Add(newRecord);
    db.SaveChanges();

    }
    //Display records
    return RedirectToAction("../home/Display/");
    }

    public ActionResult Display()
    {
    return View();
    }
    }
    }
  4. 索引查看

    @{
    ViewBag.Title = "Index";
    }

    @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
    new { enctype = "multipart/form-data" }))
    {
    <div>
    First name<br />
    @Html.TextBox("fname") <br />
    Last name<br />
    @Html.TextBox("lname") <br />
    Image<br />
    <input type="file" name="file" id="file" style="width: 100%;" /> <br />
    <input type="submit" value="Upload" class="submit" />
    </div>
    }
  5. 显示 View

    @{
    ViewBag.Title = "Display";
    }

    @{
    test2.Database1Entities db = new test2.Database1Entities();
    }
    @using (Html.BeginForm())
    {
    <table border="1">
    <thead>
    <tr>
    <th>Image</th>
    <th>First name</th>
    <th>Last name</th>
    </tr>
    </thead>
    <tbody>
    @foreach (var item in db.tblAs)
    {
    <tr>
    <td><img src="~/images/@item.imageUrl" width="100" height="100" /></td>
    <td>@item.fname</td>
    <td>@item.lname</td>
    </tr>
    }
    </tbody>
    </table>
    }

输出:

/Home/

enter image description here

/home/Display/

enter image description here

关于c# - 如何将图像保存在数据库中并将其显示到 MVC 4 中的 View 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20825119/

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