我想把上传的图片插入根目录下的图片文件夹,并把它的路径插入数据库中的图片列

本文关键字:插入 路径 数据库 根目录 文件夹 | 更新日期: 2023-09-27 18:26:25

当img部分是固定的,xxx是插入/更新产品的id,yyy是该产品不断增加的图像数量,并将imagpath列的路径存储在我的表中时,我如何通过razor语法(CSHTML)创建一个上传图像页面,简单地将文件上传到/image根,并增加名称,如imgxxxyyy.jpg?

我想得越多,研究得越多,我就越困惑。。。。在这种情况下请帮帮我。

我想把上传的图片插入根目录下的图片文件夹,并把它的路径插入数据库中的图片列

如果使用Guids作为文件名,会更容易。因此,您可以定义一个视图模型:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

一个包含表单的视图,用户可以在其中选择要上传的文件:

@model MyViewModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.LabelFor(x => x.File)
    @Html.TextBoxFor(x => x.File, new { type = "file" })
    @Html.ValidationMessageFor(x => x.File)
    <button type="submit">Upload</button>
}

最后是一个控制器来显示表单并处理上传:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }
    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (model.File != null && model.File.ContentLength > 0)
        {
            var imageFolder = Server.MapPath("~/image");
            var ext = Path.GetExtension(model.File.FileName);
            var file = Path.ChangeExtension(Guid.NewGuid().ToString(), ext);
            var fullPath = Path.Combine(imageFolder, file);
            model.File.SaveAs(fullPath);
            // Save the full path of the uploaded file
            // in the database. Obviously this code should be externalized
            // into a repository but for the purposes of this example
            // I have left it in the controller
            var connString = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;
            using (var conn = new SqlConnection(connString))
            using (var cmd = conn.CreateCommand())
            {
                conn.Open();
                cmd.CommandText = "INSERT INTO images VALUES (@path)";
                cmd.Parameters.AddWithValue("@path", fullPath);
                cmd.ExecuteNonQuery();
            }
        }
        return View(model);
    }
}