webuploader结合c# mvc实现图片上传,删除,编辑回显

前面写了个初级版的,如今总结下完整的。这里主要总结下webuploader结合c# mvc图片上传,编辑回显及删除。javascript

1、上传

一、下载WebUploader,这里主要用到如下几个文件:Uploader.swf,webuploader.css,webuploader.jscss

二、在页面引入css和jshtml

三、页面加一个用于放图片的div容器,一个添加图片的按钮和一个上传图片的按钮(由于我使用手动上传的方式,不是有文件选择就开始上传),以下:java

<div id="fileList" style="margin-left: 20px">
  </div>
 <div id="filePicker" style="margin-left: 20px">添加</div>
 <button id="ctlBtn" class="btn btn-default" style="margin-left: 10px">上传</button>

四、初始化webuploader组件web

(1)先定义一些用到的变量json

var $ = jQuery,
        $list = $('#fileList'),

        // 优化retina, 在retina下这个值是2
        ratio = window.devicePixelRatio || 1,

        // 缩略图大小
        thumbnailWidth = 350 * ratio,
        thumbnailHeight = 350 * ratio,

         // Web Uploader实例
         uploader;

        //保存从后台返回的图片url
         PhotoUrlArray = new Array();

(2)初始化webuploader组件c#

var uploader = WebUploader.create({

            // 选完文件后,是否自动上传。
             auto: false,

           //验证文件总数量, 超出则不容许加入队列
            fileNumLimit: 2,

           // swf文件路径
            swf: '~/Content/Uploader.swf',

           // 文件接收服务端。
           server: '/Product/UpLoadProcess',

           // 选择文件的按钮。可选。
           // 内部根据当前运行是建立,多是input元素,也多是flash.
           pick: '#filePicker',

           // 只容许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
            });

五、设置当文件被加入队列之后触发的事件segmentfault

uploader.on('fileQueued', function (file) {
            var $li = $(
                    '<div id="' + file.id + '" class="file-item thumbnail 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, 用样式标记上传成功。mvc

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 () {
        });

十一、 开始上传

$("#ctlBtn").click(function () {
            uploader.upload();
        });

2、删除

一、显示删除按钮

$(document).on("mouseover",".cp_img", function (){
            $(this).children(".cp_img_jian").css('display', 'block');
        });
二、隐藏删除按钮
$(document).on("mouseout",".cp_img", 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));
            for (var i = 0; i < PhotoUrlArray.length; i++) {
                if (PhotoUrlArray[i].id === Id) {
                    PhotoUrlArray.splice(i, 1);
                }
            }
            $(this).parent().remove();
        });

3、图片编辑回显

一、编辑时根据已有url模仿异步上传图片
var getFileBlob = function (url, cb) {
                var xhr = new XMLHttpRequest();
                xhr.open("GET", url);
                xhr.responseType = "blob";
                xhr.addEventListener('load', function() {
                    cb(xhr.response);
                });
                xhr.send();
            };

            var getFileObject = function(filePathOrUrl, cb) {
                getFileBlob(filePathOrUrl,cb);
            };

二、显示已有地址的图片

//须要编辑的图片列表
          var picList = ['图片url','图片url','图片url','图片url' ]
            $.each(picList, function (index, item) {
                if(item!=="")
                getFileObject(item,
                    function(fileObject) {
                        var wuFile = new WebUploader.Lib.File(WebUploader.guid('rt_'), fileObject);
                        var file = new WebUploader.File(wuFile);
                        uploader.addFiles(file);
                 });
            });

4、C#后台上传图片,使用相对路径

public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            string filePath = "~/Image/Upload/";
            if (Request.Files.Count == 0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = id });
            }
            var mapFilePath = Server.MapPath(filePath);
            if (!Directory.Exists(mapFilePath))
            {
                Directory.CreateDirectory(mapFilePath);
            }
            string ex = Path.GetExtension(file.FileName);
            var filePathName = Guid.NewGuid().ToString("N") + ex;
            string savePath = Server.MapPath(filePath+ filePathName);
            file.SaveAs(savePath);
            return Json(new { jsonrpc = "2.0", id = id, filePath = filePath + filePathName });

        }

参考地址: https://segmentfault.com/q/1010000007428390

http://fex.baidu.com/webuploader/getting-started.html

http://download.csdn.net/download/terryda/9475429#

http://www.cnblogs.com/cemaster/p/5604253.html

相关文章
相关标签/搜索