`

MVC学习之七_____上传多张图片

    博客分类:
  • MVC4
mvc 
阅读更多
图片上传控件:WebUploader

后台代码:
public ActionResult Index()
        {
            return View();
        }

        public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            string filePathName = string.Empty;
            // 获取图片存放的本地路径
            string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload");
            //说明没有拿到图片信息
            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 = "/Upload/" + filePathName
            });

        }


模板代码:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>多图片上传页</title>

    <script type="text/javascript" src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="~/Scripts/webuploader.js"></script>
    <link rel="stylesheet" href="~/Content/Upload/webuploader.css">
    <link rel="stylesheet" href="~/Content/bootstrap.min.css">
    <link rel="stylesheet" href="~/Content/Upload/demo.css">
    <link rel="stylesheet" href="~/Content/Upload/style.css">
    <link rel="stylesheet" href="~/Content/Upload/font-awesome.css">
</head>
<body>
    <div>
        <table class="tc_table_cp" border="0">
            <tr>
                <td width="104">图片上传:</td>
                <td colspan="3">
                    <div id="fileList">

                    </div><!--存放图片的容器-->
                    <div class="cp_img_jia" id="filePicker"></div>
                    <!--这是上传按钮-->
                </td>
            </tr>
            <tr>
                <td width="104"></td>
                <td colspan="3">
                    <button id="ctlBtn" class="btn btn-default">开始上传</button>
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

<script type="text/javascript">
	var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../";
	$(function() {
		var $ = jQuery,
			$list = $('#fileList'),
			// 优化retina, 在retina下这个值是2
			ratio = window.devicePixelRatio || 1,
			// 缩略图大小
			thumbnailWidth = 90 * ratio,
			thumbnailHeight = 90 * ratio,

			// Web Uploader实例
			uploader;
		uploader = WebUploader.create({
			// 选完文件后,是否自动上传。
			auto: false,

			disableGlobalDnd: true,
			// swf文件路径
			swf: applicationPath + '/Script/Uploader.swf',

			// 文件接收服务端。
            server: applicationPath + '/Upload/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');
            //alert("保存成功");   
		});

		// 文件上传失败,显示上传出错。
		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();
		});

		//显示删除按钮
		$(".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();
		});

	});
</script>




此外还用到了模板中引用的css和js代码,详见附件
备注:css中关于图片的引用请根据自己的路径,修改图片地址

参考:http://www.cnblogs.com/ismars/p/4176912.html
稍有改动,如果对此控件有兴趣可到官方了解
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics