利用JQuery上传插件Uploadify实现图片上传MongoDB并预览

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 利用JQuery上传插件Uploadify实现图片上传MongoDB并预览

引言


最近在项目中遇到这么一个需求就上当客户来报名的时候,需要将客户的照片上传显示在页面上供客户预览,还得需要将客户的图片保存在MongoDB数据库中,在开始的时候使用HTML自带的File控件,这样可以轻松的实现图片的上传和预览,但是在向MongoDB数据库存储的时候遇到了问题,就是我们在火狐浏览器中没有办法获得这张图片的路径,但是在将图片转换成字节流的时候需要这图片的地址作为参数,所以最后利用JQuery里面的一个插件再结合File控件共同来完成来完成这个功能,下面给大家分享一下:


前台页面代码:

       <table style=" border-spacing:80px;margin-left:-100px">
                <tbody>
                <tr>
                  <td>报名人照片:</td>
                   <td style="width:50px">
                       <img id="previewImag" name="pic" style="width:150px;height:200px;margin-left:-90px" src="../../Content/images/20140801123950.jpg" />
                       </td>
                    </tr>
                   </tbody>
                </table>
            <table style=" border-spacing:80px;margin-left:200px;margin-top:-380px">
                <tr>
                    <td>委托书:</td>
                    <td style="width:50px">
                        <img id="preview" name="pic" style="width:150px;height:200px;margin-left:-90px" src="../../Content/images/6793504_173507408119_2.jpg" /></td>
                </tr>
             </table>
        <table style="margin-top:-50px">
            <tr>
                <td>上 传 图 片</td>
                <td>
                    <input id="ApplyPicture" type="file" name="file_upload" hidden="hidden">
                    @*<input type="file" name="fileToUpload" id="fileToUpload2"  multiple="multiple"  />
                        <input type="submit" value="上传" οnclick="Upload()"/>
                        <input type="file" />
                        <input type="button" value="上传"/>*@
                </td>
                <td>上传委托书</td>
                <td><input id="file_upload" type="file" name="choosing"></td>
            </tr>
        </table>

我们在前台页面引入了两个image框和两个普通的File控件,界面如下:

 

js代码如下:


//上传文件的控件
$(document).ready(function () {
    $('#file_upload').uploadify({
        'swf': '../Content/uploadify.swf',                        //FLash文件路径
        'buttonText': '浏 览',                        //按钮文本
        'width': '100',                          // 按钮的宽度
        'height': '28',                         // 按钮的高度
        'uploader': '/BidTRecordManager/file_upload',           //Controller处理地址
        //'formData': { 'folder': 'picture' },         //传参数
        'fileObjName': 'Filedata',
        //'queueID': 'fileQueue',                        //队列的ID
        'queueSizeLimit': 10,                           //队列最多可上传文件数量,默认为999
        'auto': true,                                 //选择文件后是否自动上传,默认为true
        'multi': true,                                 //是否为多选,默认为true
        //'removeCompleted': true,                       //是否完成后移除序列,默认为true
        // 'fileSizeLimit': '10MB',                       //单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值
        'fileTypeDesc': '请选择*.png *.gif文件',                 //文件描述
        'fileTypeExts': '*.png;*.gif;*.jpg', //上传的文件后缀过滤器
        'onUploadComplete': function (file) {
            $.post("/BidTRecordManager/PhotoName",
          {
          }, function (result) {
              document.getElementById("preview").src = "../../Content/" + result;
          });
        }
    });
    $('#ApplyPicture').uploadify({
        'swf': '../Content/uploadify.swf',                        //FLash文件路径
        'buttonText': '浏 览',                        //按钮文本
        'width': '100',                          // 按钮的宽度
        'height': '28',                         // 按钮的高度
        'uploader': '/BidTRecordManager/UpApplyPicture',           //Controller处理地址
        //'formData': { 'folder': 'picture' },         //传参数
        'fileObjName': 'Filedata',
        //'queueID': 'fileQueue',                        //队列的ID
        'queueSizeLimit': 10,                           //队列最多可上传文件数量,默认为999
        'auto': true,                                 //选择文件后是否自动上传,默认为true
        'multi': true,                                 //是否为多选,默认为true
        //'removeCompleted': true,                       //是否完成后移除序列,默认为true
        // 'fileSizeLimit': '10MB',                       //单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值
        'fileTypeDesc': '请选择*.png *.gif *.jpg文件',                 //文件描述
        'fileTypeExts': '*.png;*.gif;*.jpg', //上传的文件后缀过滤器
        'onUploadComplete': function (file) {
            $.post("/BidTRecordManager/AppleyPhoto",
          {
          }, function (result) {
              document.getElementById("previewImag").src = "../../Content/" + result;
          });
        }
    });
});

Controller中的代码:

#region  通过js对 基本的file控件进行封装,实现报名人照片上传
<span style="white-space:pre">  </span><pre name="code" class="csharp">        public static string AppleyPhotoName = "";  //定义一个全局变量,存放报名人照片的名称
        public static string Name = "";  //定义一个全局变量,存放委托书的照片
        public ActionResult UpApplyPicture(HttpPostedFileBase Filedata)
        {
            #region 对文件信息的完整性进行检验
            // 如果没有上传文件||上传文件的文件名为空||上传文件的文件内容为空
            if (Filedata == null ||
               string.IsNullOrEmpty(Filedata.FileName) ||
               Filedata.ContentLength == 0)
            {
                return this.HttpNotFound();
            }
            #endregion
            #region 将上传文档暂时存到服务器上,方便对文件创建索引
            //获得文件名称
            string strFileName = System.IO.Path.GetFileName(Filedata.FileName);
            //上传文件暂时存放的相对(虚拟)路径
            string virtualPath =
                string.Format("../Content/{0}", strFileName);
            //上传文件暂时存放的绝对路径
            //var strPath = this.Server.MapPath(virtualPath);
            var strPath = this.Server.MapPath(virtualPath);
            AppleyPhotoName = Filedata.FileName;
            //将文件保存到该路径下
            Filedata.SaveAs(strPath);
            //Applicants();
            //return View();
            //将图片保存在mongoDB数据库中
            UpLoad(strPath, AppleyPhotoName);
            //  #region 关闭数据库连接,删除临时文件
            //MongoHelper mgHelper = new MongoHelper();
            //mgHelper.CloseMongoDB();
            判断文件是不是存在
            //if (System.IO.File.Exists(strPath))
            //{
            //    //如果存在则删除
            //    System.IO.File.Delete(strPath);
            //}
            //  #endregion
            return this.Json(new { });
            #endregion
        }
        #endregion
        #region  通过js对 基本的file控件进行封装,实现委托书上传
        public ActionResult file_upload(HttpPostedFileBase Filedata)
        {
            #region 对文件信息的完整性进行检验
            // 如果没有上传文件||上传文件的文件名为空||上传文件的文件内容为空
            if (Filedata == null ||
               string.IsNullOrEmpty(Filedata.FileName) ||
               Filedata.ContentLength == 0)
            {
                return this.HttpNotFound();
            }
            #endregion
            #region 将上传文档暂时存到服务器上,方便对文件创建索引
            //获得文件名称
            string strFileName = System.IO.Path.GetFileName(Filedata.FileName);
            //上传文件暂时存放的相对(虚拟)路径
            string virtualPath =
                string.Format("../Content/{0}", strFileName);
            //上传文件暂时存放的绝对路径
            //var strPath = this.Server.MapPath(virtualPath);
            var strPath = this.Server.MapPath(virtualPath);
            Name = Filedata.FileName;
            //将文件保存到该路径下
            Filedata.SaveAs(strPath);
            //Applicants();
            //return View();
            //将图片保存在mongoDB数据库中
            UpLoad(strPath,Filedata.FileName);
            //  #region 关闭数据库连接,删除临时文件
            //MongoHelper mgHelper = new MongoHelper();
            //mgHelper.CloseMongoDB();
            判断文件是不是存在
            //if (System.IO.File.Exists(strPath))
            //{
            //    //如果存在则删除
            //    System.IO.File.Delete(strPath);
            //}
            //  #endregion
            return this.Json(new { });
            #endregion
        }
        #endregion
        #region    将图片保存在mongoDB数据库中 郑浩 2015年7月11日
        public string UpLoad(string fileName, string Photoname)
        {
            MongoHelper mgHelper = new MongoHelper();
            Document doc = new Document();
            FileStream fs = null;
            fs = new FileStream(fileName, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
            Bitmap bt = new Bitmap(fs);
            int streamLength = (int)fs.Length;
            byte[] image = new byte[streamLength];
            fs.Read(image, 0, streamLength);
            doc["ID"] = Guid.NewGuid();
            doc["Img"] = image;
            doc["Name"] = Photoname;
            mgHelper.MongoCollection.Save(doc);
            return "图片保存呢成功";
        }
        #endregion
        #region  获取委托书照片的名称
        /// <summary>
        /// 获取照片的名称
        /// </summary>
        /// <returns></returns>
        public string PhotoName()
        {
            //Response.Write(strPath1);  
            return Name;
            #region 关闭数据库连接,删除临时文件
            //MongoHelper mgHelper = new MongoHelper();
            //mgHelper.CloseMongoDB();
            判断文件是不是存在
            //if (System.IO.File.Exists(strPath1))
            //{
            //    //如果存在则删除
            //    System.IO.File.Delete(strPath1);
            //}
            //#endregion
        }
        #endregion
        #region  获取报名人照片的名称
        /// <summary>
        /// 获取照片的名称
        /// </summary>
        /// <returns></returns>
        public string AppleyPhoto()
        {
            //Response.Write(strPath1);  
            return AppleyPhotoName;
            //#region 关闭数据库连接,删除临时文件
            //MongoHelper mgHelper = new MongoHelper();
            //mgHelper.CloseMongoDB();
            判断文件是不是存在
            //if (System.IO.File.Exists(strPath1))
            //{
            //    //如果存在则删除
            //    System.IO.File.Delete(strPath1);
            //}
            //#endregion
        }
        #endregion

通过上面这三个部分的代码我们就解决了这个问题,基本上实现了这个需求,但是自己感觉这个方法应该不是最简单的一种,因为我们可以看到在我们向MongoDB数据库中存储的时候,在将图片转换成字节流的过程中,我们首先将图片上传到了服务器上,然后获得了一个绝对路径后才完成的这个功能,所以希望读者能给予一种新的做法,从而可以很好优化这个代码。

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
6月前
|
JavaScript
Jquery插件知识之Jquery.cookie实现页面传值
Jquery插件知识之Jquery.cookie实现页面传值
36 0
|
3月前
|
JavaScript
jQuery图片延迟加载插件jQuery.lazyload
jQuery图片延迟加载插件jQuery.lazyload
|
3月前
|
JavaScript 数据可视化 前端开发
jQuery-JS插件-第9次课-使用插件让领导对你刮目相看-附案例作业
jQuery-JS插件-第9次课-使用插件让领导对你刮目相看-附案例作业
19 0
|
3月前
|
JavaScript 前端开发
开发jQuery插件这些就够了
开发jQuery插件这些就够了
28 0
|
4月前
|
JavaScript 前端开发 安全
jQuery 第十一章(表单验证插件推荐)
jQuery 第十一章(表单验证插件推荐)
56 1
|
5月前
|
JavaScript
jQuery年月日(年龄)选择插件
jQuery年月日(年龄)选择插件
28 0
|
5月前
|
前端开发 JavaScript
Jquery前端分页插件pagination同步加载和异步加载
Jquery前端分页插件pagination同步加载和异步加载
44 0
|
5月前
|
JavaScript 前端开发 数据格式
Jquery前端分页插件pagination使用
Jquery前端分页插件pagination使用
64 1
|
5月前
|
移动开发 JavaScript 前端开发
jQuery实现多种切换效果的图片切换的五款插件
jQuery实现多种切换效果的图片切换的五款插件
40 0
|
5月前
|
移动开发 JSON JavaScript
七个帮助你处理Web页面层布局的jQuery插件
七个帮助你处理Web页面层布局的jQuery插件
44 0