图片处理

* MVC图片

见博客https://blog.csdn.net/shan1774965666/article/details/51302087

  注:数据中可以存储图片,但是需要注意不能直接存储图片,而是转换成二进制或者Base64等的“文本”来存储,在用的时候,可以再转换回来。
               在网站开发中,一般将图片存储在文件系统中,而不是数据系统中,数据库系统中只记录图片在文件系统中的路径而已。

  缺点:如果数据库中只存文件路径,那么定时删除的只是路径,图片还在系统中保存

       如果是转成二进制存储,存入和读取比较麻烦,浪费资源。

 实现思路大概分为两步:

1. 通过上传接口,将图片上传到服务器,返回文件路径给客户端;

2. 点击保存上传,将文件路径保存到数据库,如果是多张图片,路径用逗号分隔。

1.  上传保存到本地

保存至项目中,同时保存至本地

<div class="panel-body">
    <form action="/db/Uploading" method="post" enctype="multipart/form-data">
        <input type="file" name="file1"/>
        <input type="submit"value="submit"/>
    </form>
</div>
html
   [HttpPost]
        public ActionResult Uploading()
        {
            if (Request.Files.Count > 0)
            {
                //得到选择上传的图片
                HttpPostedFileBase f = Request.Files["file1"];
                if (f != null && f.ContentLength > 0)
                {
                    //文件大小
                    if (f.ContentLength > 5242880)
                        return Content("<script>alert('错误提示:文件大小超出指定范围!');</script>");

                    string fileName = f.FileName;

                    //文件扩展名
                    string ext = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
                    if (ext == ".jpg" || ext == ".png")
                    {
                        //与 Web 服务器上的指定虚拟路径相对应的物理文件路径
                        string path = Server.MapPath("~/img");
                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);

                        //重新构建文件名
                        fileName = DateTime.Now.ToFileTime().ToString() + Guid.NewGuid().ToString("N") + ext;

                        //保存文件到项目
                        var picPath = Path.Combine(path, fileName);
                        f.SaveAs(picPath);
                    }
                    else
                        return Content("<script>alert('错误提示:上传的文件格式不正确!');</script>");
                }
                else
                    return Content("<script>alert('错误提示:上传的文件是空文件!');</script>");
              
                //将图片保存到本地
                f.SaveAs(@"C:\Users\17612\Desktop\"+ f.FileName);
            }
            return Json(1);
        }
后台代码

2. 上传保存到数据

效果图:本地上传后,保存到数据库

2.1 数据库的设计

--数据库设计
create table t_imagestore(
    f_id int identity(1,1) not null primary key,
    f_name varchar(50) not null,
    f_type varchar(50) not null,
    f_content image not null  -- 设计为image类型
)

--添加数据
go
create procedure pro_imagestore_insert(
    @f_name varchar(50),
    @f_type varchar(50),
    @f_content image
)
as
insert into t_imagestore values (@f_name, @f_type, @f_content)


--查询数据
go 
create procedure pro_imagestore_getAll
as
select * from t_imagestore with(nolock)
View Code

2.2 执行存储过程的帮助类

        #region 执行存储过程
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(Constr))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }

        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure; //存储过程类型
            foreach (SqlParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        } 
        #endregion
SqlHelper 

2.3 前台页面

<div style="width:1200px; margin-left:30px">
    <table style="width:100%">
        <tr>
            <td valign="top">
                <fieldset style="text-align:left">
                    <legend>上传</legend>
                    <form action="UploadFile" method="post" enctype="multipart/form-data">
                        <input type="file" name="fileName" id="file1" /><br />
                        <input type="submit" value="submit" />
                    </form>
                </fieldset>
            </td>
            <td>
                <fieldset>
                    <legend>预览</legend>
                    <div style="width:200px;height:160px">
                        <img id="img1" src="" alt="预览图片"  />
                    </div>
                </fieldset>
            </td>
        </tr>
    </table>
    <fieldset>
        <legend>显示</legend>
        <div style="width:100%;height:300px;overflow-x:hidden;overflow-y:auto">
            <table style="width:100%; text-align:center" class="table-bordered" >
                <tr>
                    <th>编辑</th>
                    <th>删除</th>
                    <th>ID</th>
                    <th>FileName</th>
                    <th>type</th>
                    <th>image</th>
                </tr>
                @foreach (var mod in Model)
                {
                    <tr>
                        <td><button value="1" onclick="UpdateImg(@mod.f_id)">更新</button></td>
                        <td><button value="1" onclick="DeleteImg(@mod.f_id)">删除</button></td>
                        <td>@mod.f_id</td>
                        <td>@mod.f_name</td>
                        <td>@mod.f_type</td>
                        <td>
                            <img src="data:@mod.f_type;base64,@Convert.ToBase64String(mod.f_content)" />
                        </td>
                    </tr>
                }
            </table>
        </div>
    </fieldset>
</div>
<script>
    $(function () {
        //选择文件的change事件
        $("#file1").on("change", function () {
            var file = this.files[0];
            if (this.files && file) {
                var reader = new FileReader();

                //将file加载到img1
                reader.onload = function (e) {
                    $("#img1").attr("src", e.target.result);
                }
                reader.readAsDataURL(file);
            }
        })
    })

    function UpdateImg(id) {
        layer.open({
            type: 2,
            title: ['图片拖拽', 'color:red'],
            area: ['1000px','800px'],
            content:"@Url.Action("DragPicture")"
        })
    }
</script>
View Code

2.4 后台代码

        public ActionResult ShowImage()
        {
            DataSet ds = SqlHelper.RunProcedure("pro_imagestore_getAll", new IDataParameter[] { }, "t_imagestore");
            List<ImageStore> list = ConvertHelper<ImageStore>.ConvertToList(ds.Tables[0]);
            return View(list);
        }

//上传
        [HttpPost]
        public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> filename)
        {
            foreach(var file in filename)
            {
                if(file.ContentLength > 0)
                {
                    ImageStore mod = new ImageStore();
                    mod.f_name = Path.GetFileName(file.FileName);
                    mod.f_type = file.ContentType;

                    using (Stream input = file.InputStream)
                    {
                        //判断input是否为null
                        MemoryStream ms = input as MemoryStream;
                        if(ms == null)
                        {
                            ms = new MemoryStream();
                            input.CopyTo(ms);
                        }
                        mod.f_content = ms.ToArray();
                    }

                    //执行存储过程添加到数据库中
                    SqlParameter[] pars = new SqlParameter[]
                    {
                        new SqlParameter("@f_name",mod.f_name),
                        new SqlParameter("@f_type",mod.f_type),
                        new SqlParameter("@f_content",mod.f_content)
                    };
                    SqlHelper.RunProcedure("pro_imagestore_insert", pars, "t_imagestore");
                }
            }
            return RedirectToAction("ShowImage"); //重定向到查询的控制器
        }
View Code

 

 
posted on 2018-08-01 11:41  莫伊筱筱  阅读(191)  评论(0编辑  收藏  举报