ASP.NET--图片上传通过二进制保存到数据库

ASP.NET–图片上传通过二进制保存到数据库

开发工具:Visual Studio 2015、SQL Server 2014 Management Studio

关键技术:C# MVC
作者:刘东标
撰写时间:2019年1月18日
1、以二进制存储的话,较安全,图片存到数据库里面后,服务器端就没有文件夹存储图片了,网页中显示的图片都是来自数据库(所以读取图片稍微有点麻烦)。
2、保存路径的话,读存很容易,数据库也相对较小,服务器端还的有文件夹来保存这些图片(上传),所以一旦文件夹不小心丢失,所有图片就找不回了。
相对于网页开发者来说,保存路径相对容易些,但是都不会那么做的,所以网站的图片一般是以二进制保存到数据库!_
3、如何是要大量上传图片的,推荐使用保存路径到数据库比较好,二进制保存大量图片会使数据库炸掉!

实现效果:

在这里插入图片描述

在这里插入图片描述

、、、、、、、、、、、、、html代码、、、、、、

  @*选择文件*@
                            <div class="Education_two hide">
                                <span>学历信息</span>
                                <form action="/MyAccount/MyAccount/UpdateEducation" method="post" id="formSelectExaminee">
                                    <input type="hidden" name="ClientID" value=" " />
                                    <input type="hidden" name="EducationID" value=" " />
                                    <div class="col-md-12 col-sm-12" style="margin-left:100px;">
                                        <img src="" alt="" width="150" height="180" id="IimgStudentPicture" />
                                        <input type="file" name="fileStudentImage" style="width:72px;height:22px;border:none;" id="IStudentPicture" />
                                        <span>未选择任何文件</span>
                                    </div>
                                    <div class="col-md-12 col-sm-12">
                                        <label>用户名:</label>
                                        <input type="text" name="UserName" value="@Session["UserName"]" class="disn" readonly />
                                    </div>
                                    <div class="col-md-12 col-sm-12">
                                        <label>真实姓名:</label>
                                        <input type="text" name="TrueClientName" class="disn" readonly />
                                    </div>
                                    <div class="col-md-12 col-sm-12">
                                        <label>毕业院校:</label>
                                        <input type="text" name="School" />
                                    </div>
                                    <div class="col-md-12 col-sm-12">
                                        <label>专业:</label>
                                        <input type="text" name="Specialty"  />
                                    </div>
                                    <div class="col-md-12 col-sm-12">
                                        <label>学历:</label>
                                        <input type="text" name="EducationBackground"  />
                                    </div>
                                    <div class="col-md-12 col-sm-12">
                                        <label>入学时间:</label>
                                        <input type="date" name="EntranceDate" id="EntranceDate"  />
                                    </div>
                                    <div class="col-md-12 col-sm-12">
                                        <label>毕业年份:</label>
                                        <input type="date" name="GraduateDate" id="GraduateDate" />
                                    </div>
                                    <div class="form-group" style="margin-left:100px;">
                                        <button id="Reset" type="reset" class="btn btn-primary">重置</button>
                                        <button id="SubmitOne" type="button" class="btn btn-primary">确定</button>
                                        <button id="goHome1" type="button" class="btn btn-danger">关闭</button>
                                    </div>
                                </form>
                            </div>

、、、、、、、、、、、、、js代码、、、、、、、、、、、、

        //学历认证--新增
        $("#SubmitOne").click(function () {
            var School = $("#formSelectExaminee input[name='School']").val();
            var Specialty = $("#formSelectExaminee input[name='Specialty']").val();
            var EducationBackground = $("#formSelectExaminee input[name='EducationBackground']").val();
            var EntranceDate = $("#formSelectExaminee input[name='EntranceDate']").val();
            var EntranceDate = $("#formSelectExaminee input[name='EntranceDate']").val();
            var Picture = $('#formSelectExaminee [name="fileStudentImage"]').prop('files');//照片
            //判断一些必填项的数据是否为空
            if (School != "" && Specialty != ""
              && EducationBackground != "" && EntranceDate != ""
              && EntranceDate != '') {
                //显示 加载层(是第三方对话框的属性)
                var layerIndex = layer.load(0);
                //ajaxSubmit()提交表单:我们直接通过form提交的话, 提交后当前页面跳转到form的action所指向的页面。
                //然而,很多时候我们并不希望提交表单后页面跳转,那么,我们就可以使用ajaxSubmit(obj)来提交数据
                //ajaxSubmit(obj)方法是jQuery的一个插件jquery.form.js里面的方法,所以使用此方法需要先引入这个插件
                $("#formSelectExaminee").ajaxSubmit(function (msg) {
                    layer.close(layerIndex);//关闭加载层
                    layer.alert(msg, { icon: 6, title: '提示' });
                    //重置表单
                    $('#formSelectExaminee [type="reset"]').click();
                });
            }
            else {
                layer.alert('请填写完整', { icon: 0, title: '提示' });
            }
        })
        //FileReader接口提供了一个异步的API,通过这个API可以从浏览器中异步访问文件系统中的数据。因此,FileReader接口可以读取文件中的数据,并将读取的数据放入到内存中去
        //选择照片:用FileReader对象来读取本地数据,并且将数据结果赋值给image的src、
        //图片文件 正则表达式过滤
        var imgReaderI = new FileReader();//FileReader()接口:用于读取文件
        //图片文件: 正则表达式过滤(此表达式是用来判断上传的文件是否是一张图片)
        regexImageFilter = /^(?:image\/bmp|image\/png|image\/jpeg|image\/jpg)$/i;
        //调用FileReader接口的onload方法,回调函数得到的evt是图片的URL链接
        imgReaderI.onload = function (evt) {
            //将数据结果赋值给image的src
            $("#IimgStudentPicture").attr('src', evt.target.result);
        }
        //获取“选择文件”的按钮,调用改变事件
        $("#IStudentPicture").change(function () {
            //获取通过“选择文件”的按钮上传的文件
            //prop添加属性名称(跟attr属性一样是给标签添加属性,但是它们是有区别的),加载image标签中
            var imgfFile = $("#IStudentPicture").prop('files')[0];
            //调用正则表达式过滤图片
            if (!regexImageFilter.test(imgfFile.type)) {
                layer.msg('选择的不是一个有效的图片文件', { icon: 0 });
            } //readAsDataURL()方法可以获取API异步读取的文件数据,另存为数据URL;将该URL绑定到img标签的src属性上,就可以实现图片的上传预览效果了。
            imgReaderI.readAsDataURL(imgfFile);

        })

、、、、、、、、、、、controller控制器代码、、、、、、、

  //学历认证--数据回填用户ID
        public ActionResult SelectEducationInfo(int UserID)
        {
            try
            {
                var list = (from tbEducation in myModel.S_Education
                            join tbClient in myModel.S_Client on tbEducation.ClientID equals tbClient.ClientID
                            where tbClient.UserID == UserID
                            select new
                            {
                                ClientID = tbEducation.ClientID,
                                EducationID = tbEducation.EducationID,
                                TrueClientName = tbClient.TrueClientName,
                                Picture = tbEducation.Picture,
                            }).ToList();
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }
        //学历认证
        public ActionResult UpdateEducation(S_Education education, HttpPostedFileBase fileStudentImage)
        {
            string strMsg = "学历认证失败";
            try
            {
                var list = (from tbEducation in myModel.S_Education
                            join tbClient in myModel.S_Client on tbEducation.ClientID equals tbClient.ClientID
                            where tbClient.ClientID == education.ClientID
                            select tbEducation).Single();
                if (list.Picture  != null)
                {
                    strMsg = "已经认证,学历认证失败";
                }
                else
                {
                    if (fileStudentImage != null && fileStudentImage.ContentLength > 0)
                    {
                        byte[] imgFile = null;//读取上传的图片
                                              //判断是否上传图片(判断图片的值 && 判断图片的长度)
                                              //有上传图片
                        imgFile = new byte[fileStudentImage.ContentLength];//初始化为图片的长度//读取该图片文件//将图片转为流结束位置
                                                                           //将流读取为byte[],参数:byte[],读取开始位置,读取字节数
                        fileStudentImage.InputStream.Read(imgFile, 0, fileStudentImage.ContentLength);
                        education.Picture = imgFile;
                    }
                    list.EducationBackground = education.EducationBackground;
                    list.School = education.School;
                    list.Specialty = education.Specialty;
                    list.EntranceDate = education.EntranceDate;
                    list.GraduateDate = education.GraduateDate;
                    list.Picture = education.Picture;
                    myModel.Entry(list).State = System.Data.Entity.EntityState.Modified;
                    myModel.SaveChanges();
                    strMsg = "学历认证成功";

                }
            }
            catch (Exception e)
            {

                throw;
            }
            return Json(strMsg, JsonRequestBehavior.AllowGet);
        }
        //根据studentId查询学历照片(学历ID)
        public ActionResult GetStudentImage(int UserID)
        {
            try
            {
                var list = (from tbEducation in myModel.S_Education
                            join tbClient in myModel.S_Client on tbEducation.ClientID equals tbClient.ClientID
                            where tbClient.UserID == UserID
                            select new
                                  {
                                tbEducation.Picture
                                  }).Single();
                byte[] imageData = list.Picture;
                return File(imageData, @"image/jpg");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }
        //查看学历
        public ActionResult SelectEducation(int UserID)
        {
            try
            {
                var list = (from tbEducation in myModel.S_Education
                            join tbClient in myModel.S_Client on tbEducation.ClientID equals tbClient.ClientID
                            where tbClient.UserID == UserID
                            select new
                            {
                                tbEducation.Specialty,
                                tbEducation.School,
                                GraduateDate = tbEducation.GraduateDate.ToString(),
                                EntranceDate = tbEducation.EntranceDate.ToString(),
                                tbEducation.EducationBackground,
                                tbClient.TrueClientName,
                                tbEducation.Picture,
                            }).Single();
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {

                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
图片的常见存储与读取凡是有以下几种: 存储图片:以二进制的形式存储图片时,要把数据库中的字段设置为Image数据类型(SQL Server),存储的数据是Byte[]. 1.参数是图片路径:返回Byte[]类型: public byte[] GetPictureData(string imagepath) { /**/////根据图片文件的路径使用文件打开,并保存为byte[] FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法 byte[] byData = new byte[fs.Length]; fs.Read(byData, 0, byData.Length); fs.Close(); return byData; }2.参数类型是Image对象,返回Byte[]类型: public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto) { //将Image转换成数据,并保存为byte[] MemoryStream mstream = new MemoryStream(); imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp); byte[] byData = new Byte[mstream.Length]; mstream.Position = 0; mstream.Read(byData, 0, byData.Length); mstream.Close(); return byData; }好了,这样通过上面的方法就可以把图片转换成Byte[]对象,然后就把这个对象保存数据库中去就实现了把图片的二进制格式保存数据库中去了。下面我就谈谈如何把数据库中的图片读取出来,实际上这是一个相反的过程。 读取图片:把相应的字段转换成Byte[]即:Byte[] bt=(Byte[])XXXX 1.参数是Byte[]类型,返回值是Image对象: public System.Drawing.Image ReturnPhoto(byte[] streamByte) { System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); return img; }2.参数是Byte[] 类型,没有返回值,这是针对asp.net中把图片从输出到网页上(Response.BinaryWrite) public void WritePhoto(byte[] streamByte) { // Response.ContentType 的默认值为默认值为“text/html” Response.ContentType = "image/GIF"; //图片输出的类型有: image/GIF image/JPEG Response.BinaryWrite(streamByte); }补充: 针对Response.ContentType的值,除了针对图片的类型外,还有其他的类型: Response.ContentType = "application/msword"; Response.ContentType = "application/x-shockwave-flash"; Response.ContentType = "application/vnd.ms-excel";另外可以针对不同的格式,用不同的输出类型以适合不同的类型: switch (dataread("document_type")) { case "doc": Response.ContentType = "application/msword"; case "swf": Response.ContentType = "application/x-shockwave-flash"; case "xls": Response.ContentType = "application/vnd.ms-excel"; case "gif": Response.ContentType = "image/gif"; case "Jpg": Response.ContentType = "image/jpeg"; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值