我想将上传的图像插入根目录图像文件夹及其到数据库中图像列的路径

时间:2012-03-02 22:58:31

标签: c# asp.net-mvc-3 sql-server-2008 razor

如何通过razor语法(CSHTML)创建上传图片页面,只需将img部分修复为xg是插入/更新产品的ID,就可以将文件上传到/ image root,名称如imgxxxyyy.jpg yyy是该产品的图像数量越来越多,并存储到我的表格中的imagpath列的路径?

更多我想到它并且我研究它我变得更加困惑....请在这种情况下帮助我。

1 个答案:

答案 0 :(得分:2)

如果您使用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);
    }
}