• 【项目相关】MVC中使用WebUploader进行图片预览上传以及编辑


      项目中需要用到多图片上传功能,于是在百度搜了一下,首先使用了kissy uploader,是由阿里前端工程师们发起创建的一个开源 JS 框架中的一个上传组件。。。但,后面问题出现了。

     在对添加的信息进行重新编辑的时候,这些图片怎么办?由于对js不是很熟悉,就没有想去修改这个组件的代码。只有重新寻找合适的组件,于是就找到了百度的WebUploader,下面简要描述一下该组件在MVC中的使用,包括图片的上传和预览,以及在编辑界面对图片的处理办法。

      先来一张效果图:

      

    (一)图片的上传和预览

      (1)下载WebUploader

      (2)将下载的文件添加到你的项目中,一般这几个就够了   

        <script src="~/Script/jquery-1.8.2.min.js"></script>
        <!--引入Css-->
        <link href="~/CSS/webuploader.css" rel="stylesheet" />
        <!--引入Js-->
        <script src="~/Script/webuploader.js"></script>  

      (3)在视图上放一个放图片的容器,以及一个选择图片文件的按钮

    <div id="fileList">  </div>
      <div class="cp_img_jia" id="filePicker"></div>

      (4)然后就是用js来初始化WebUploader,这段代码主要也是借鉴了网上的一个Demo,找不到出处了,在此表示感谢。 

     var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
        var $ = jQuery,
            $list = $('#fileList'),
          ratio = window.devicePixelRatio || 1,
          // 缩略图大小
          thumbnailWidth = 90 * ratio,
          thumbnailHeight = 90 * ratio,
    
          // Web Uploader实例
          uploader;
        $(function () {
            uploader = WebUploader.create({
                // 选完文件后,是否自动上传。
                auto: true,
    
                disableGlobalDnd: true,
                // swf文件路径
                swf: applicationPath + '/Script/Uploader.swf',
    
                // 文件接收服务端。
                server: applicationPath + '/EstSource/UpLoadProcess',
    
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建,可能是input元素,也可能是flash.
                pick: '#filePicker',
    
                //只允许选择图片
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/*'
                }
            });
    
            // 当有文件添加进来的时候
            uploader.on('fileQueued', function (file) {
                var $li = $(
                        '<div id="' + file.id + '" class="cp_img">' +
                            '<img>' +
                        '<div class="cp_img_jian"></div></div>'
                        ),
                    $img = $li.find('img');
    
    
                // $list为容器jQuery实例
                $list.append($li);
    
                // 创建缩略图
                // 如果为非图片文件,可以不用调用此方法。
                // thumbnailWidth x thumbnailHeight 为 100 x 100
                uploader.makeThumb(file, function (error, src) {
                    if (error) {
                        $img.replaceWith('<span>不能预览</span>');
                        return;
                    }
                    $img.attr('src', src);
                }, thumbnailWidth, thumbnailHeight);
            });
    
            // 文件上传过程中创建进度条实时显示。
            uploader.on('uploadProgress', function (file, percentage) {
                var $li = $('#' + file.id),
                    $percent = $li.find('.progress span');
    
                // 避免重复创建
                if (!$percent.length) {
                    $percent = $('<p class="progress"><span></span></p>')
                            .appendTo($li)
                            .find('span');
                }
    
                $percent.css('width', percentage * 100 + '%');
            });
    
            // 文件上传成功,给item添加成功class, 用样式标记上传成功。
            uploader.on('uploadSuccess', function (file, response) {
    
                $('#' + file.id).addClass('upload-state-done');
                //将上传的url保存到数组
                PhotoUrlArray.push(new PhotoUrl(response.id, response.filePath));
            });
    
            // 文件上传失败,显示上传出错。
            uploader.on('uploadError', function (file) {
                var $li = $('#' + file.id),
                    $error = $li.find('div.error');
    
                // 避免重复创建
                if (!$error.length) {
                    $error = $('<div class="error"></div>').appendTo($li);
                }
    
                $error.text('上传失败');
            });
    
            // 完成上传完了,成功或者失败,先删除进度条。
            uploader.on('uploadComplete', function (file) {
                $('#' + file.id).find('.progress').remove();
            });
    
            //所有文件上传完毕
            uploader.on("uploadFinished", function ()
            {
            });//显示删除按钮
            $(".cp_img").live("mouseover", function ()
            {
                $(this).children(".cp_img_jian").css('display', 'block');
    
            });
            //隐藏删除按钮
            $(".cp_img").live("mouseout", function () {
                $(this).children(".cp_img_jian").css('display', 'none');
    
            });
            //执行删除方法
            $list.on("click", ".cp_img_jian", function ()
            {
    
                var Id = $(this).parent().attr("id");
                //删除该图片
                uploader.removeFile(uploader.getFile(Id, true));
                $(this).parent().remove();
            });
        });

    这段js代码是用在上传图片界面,主要思路如下:

      1)设置图片为自动上传:auto: true,

      2)每次返回的json对象保存起来,代码如下:

           //保存从后台返回的图片url
                    var PhotoUrlArray = new Array();
                    function PhotoUrl(id, filePath) {
                        this.id = id;
                        this.filePath = filePath;
                    }
    ......
             // 文件上传成功执行方法
                    uploader.on('uploadSuccess', function (file, response) {
                        $('#' + file.id).addClass('upload-state-done');
                         //将上传的url保存到数组
                        PhotoUrlArray.push(new PhotoUrl(response.id, response.filePath));
                        });

       3)这里需要注意的是,当用户上传图片后,有可能会进行删除图片操作,所以需要在该事件里面,将json对象数组里面相对应的元素进行删除操作:

                 //执行删除方法
                        $list.on("click", ".cp_img_jian", function ()
                        {
    
                            var Id = $(this).parent().attr("id");
                            //删除该图片
                                uploader.removeFile(uploader.getFile(Id, true));
                                for (var i = 0; i < PhotoUrlArray.length; i++) {
                                    if (PhotoUrlArray[i].id == Id) {
                                        PhotoUrlArray.remove(i);
                                    }
                            }
                            $(this).parent().remove();
                        });                

    (5)视图的代码就差不多了,现在在Controller里新建一个Action用于保存图片并返回图片路径,由于该组件是一个文件一个文件的上传到服务端,所以,在用户没有点击保存的情况下,上传的图片只能保存到临时文件夹里面,当用户保存全部信息的时候,将保存到临时文件夹的文件移动到正式文件夹,并保存相对应的图片url到数据库。

     public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
            {
                //保存到临时文件夹
                string urlPath = "../Upload/temp";
                string filePathName = string.Empty;
    
                string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload/temp");
                if (Request.Files.Count == 0)
                {
                    return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
                }
    
                string ex = Path.GetExtension(file.FileName);
                filePathName = Guid.NewGuid().ToString("N") + ex;
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                file.SaveAs(Path.Combine(localPath, filePathName));
    
                return Json(new
                {
                    jsonrpc = "2.0",
                    id = id,
                    filePath = urlPath + "/" + filePathName//返回一个视图界面可直接使用的url
                });
    
            }

      (二)编辑视图界面图片的处理

      (1)主要思路:在对信息进行编辑的时候,也需要使用该控件来上传图片,所以为了保持和上传图片预览格式一致,需要在初始化的时候,将后台传回的图片显示在图片容器里面。

          <div id="fileList">
                    @foreach (var item in @ViewBag.picList)
                           {
                            <div id=@item.picId class="cp_img">
                            <img src="@item.picUrl" />
                             <div class="cp_img_jian"></div>
                  </div>
              }
           </div>

        除了这里初始化预览图片外,还需要在获取图片url的方法上进行改造,这里就是关键。在视图里,有一个实体属性PhotoUrl用来保存所有的url图片。

     function GetPhotoUrl() {
            var photoUrls = "";
            $("#fileList img").each(function (i) {
                if ($(this).attr("src").indexOf('UpLoad/photos/') > 0) {
                    photoUrls = photoUrls + $(this).attr("src")+",";
                }
            });
            for (var i = 0; i < PhotoUrlArray.length; i++) {
                photoUrls = photoUrls + PhotoUrlArray[i].filePath;
            }
            $("#PicUrls").val(photoUrls);
        }

    这个方法在上传视图中也是用来保存图片urls的,大同小异,稍微修改一下就行。

    (2)后端上传服务都是使用的一个Action,没有不同的地方,主要的区别是在保存的时候对图片url的处理上,每个系统都不一样,这里就不叙述了。

     

    总结:项目做了几个了,可技术总没有提升上去,得突破自己才行!从现在开始,记录每一个在项目中值得记录的东西。

     补充一下!!!

    最近有很多人加我,想要这个源码,我在这里提供百度云盘链接,需要的请自己下载!谢谢。。。

       链接:http://pan.baidu.com/s/1jHXziZ0 密码:q919

  • 相关阅读:
    eclispe安装tomcate没有srver解决
    反射常见方法
    让用户输入一个日期字符串,将其转换成日期格式, 格式是(yyyy/MM/dd,yyyyMMdd,yyyy-MM-dd)中的一种, 任何一种转换成功都可以; 如果所有的都无法转换,输出日期格式非法。
    List 接口中ArrayList Vector LinkedList 比较
    抽象类
    js核心知识
    JQgrid学习网站
    小练习---递归求5!
    map()
    小练习---阶乘
  • 原文地址:https://www.cnblogs.com/cemaster/p/5604253.html
Copyright © 2020-2023  润新知