webupload 插件使用
主要流程:1.引入插件 2.增加后台服务(上传文件服务,返回路径给前端) 3.将返回的文件名 保存到前端的隐藏域 跟着表单提交一起提交到后台 4.图片回显(主要将图片转为文件)。
(一)图片的上传和预览
(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。
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(); });
4)图片的回显:
//图片转为文件
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 blobToFile = function (blob, name) {
blob.lastModifiedDate = new Date();
blob.name = name;
return blob;
};
var getFileObject = function(filePathOrUrl, name,cb) {
getFileBlob(filePathOrUrl, function (blob) {
cb(blobToFile(blob, name));
});
};
var picList = new Array(),info = '';
//已有图片初始化
<{if isset($attacheds)}>
<{foreach from=$attacheds item=att name=att}>
info = <{$att.json}>;
var a = new Object();
a.fileName = info.fileName;
a.src = info.src;
picList.push(a);
<{/foreach}>
<{/if}>
$.each(picList, function(index,item){
getFileObject(item.src,item.fileName, function (fileObject) {
var wuFile = new WebUploader.Lib.File(WebUploader.guid('rt_'),fileObject);
var file = new WebUploader.File(wuFile);
uploader.addFiles(file)
})
});