且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将上传图片直接保存至SQL Server数据库中

更新时间:2021-11-20 08:27:19

这里演示的是如何将上传图片直接保存至SQL Server数据库中。

  在数据库中,图片使用varbinary(MAX)存储:

如何将上传图片直接保存至SQL Server数据库中

  这是个基于MVC3架构的例子。废话不多说,直接上代码:

  View:

@{
    ViewBag.Title = "UpLoadImg";
}
@using (Html.BeginForm("Create", "UpLoadImg", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <h2>
        UpLoadImg</h2>
    <div id="mainform">
        <div>
            <input type="file" id="UpLoadFile" name="UpLoadFile" />
            <input id="btnUpLoad" type="submit" value="上传" />
        </div>
        <div>
        </div>
    </div>
}

  Controller后台Action:

public ActionResult Create()
        {
            string filename = string.Empty;
            string filetype=string.Empty;
            byte[]  filecontext=null;
            HttpPostedFileBase filebase = Request.Files["UpLoadFile"];
            if (filebase.ContentLength > 0)
            {
                Stream stream = filebase.InputStream;
                byte[] by = new byte[filebase.ContentLength];
                int i = stream.Read(by,0,filebase.ContentLength);
                stream.Close();
                string[] arrs = filebase.FileName.Split('\\');
                if (arrs.Length > 0)
                {
                    filename = arrs[arrs.Length - 1];
                }
                else
                {
                    filename = filebase.FileName;
                }
                filetype=filebase.ContentType;
                filecontext=by;
            }//淡雅一抹繁华,几多思念许他,他不知花开不易,他不懂人心需要珍惜。
            int count = 0;
            #region 插入数据
            try
            {
                string ImageStore = System.Configuration.ConfigurationManager.AppSettings["ConnectionStrImageStore"].ToString().Trim();
                string sqlStr = string.Empty;
                sqlStr = @"INSERT INTO [Images] ([filename],[filetype],[filecontext],[uploadtime])
                    VALUES(@filename,@filetype,@filecontext,@uploadtime)";
                SqlConnection connection = new SqlConnection(ImageStore);
                SqlCommand command = new SqlCommand(sqlStr, connection);
                command.Parameters.AddWithValue("@filename",filename);
                command.Parameters.AddWithValue("@filetype",filetype);
                command.Parameters.AddWithValue("@filecontext",filecontext);
                command.Parameters.AddWithValue("@uploadtime",DateTime.Now);
                command.Connection.Open();
                count=command.ExecuteNonQuery();
                command.Connection.Close();
            }
            catch
            {
               
            }
            #endregion

            if (count > 0)
            {
                return RedirectToAction("UpLoadImg");
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

   



最新内容请见作者的GitHub页:http://qaseven.github.io/