C# MVC(File)控件多张图片上传加预览

时间:2023-03-08 19:31:31
C# MVC(File)控件多张图片上传加预览

刚来公司实习,老板叫我写一个积分商城网站。用的是公司的框架结构搭建的后台,所以后台的图片上传不需要自己写。但是前台的评价图片就需要自己手写了,在网上找了很多代码发现都用不了。问了很多人也都没有实现!

最后公司同事给我了一个上传的代码,拿来借用。发现效果很好,困扰了我很多天的问题,也得于解决。现在我把他分享出来!

先看一下上传效果:

界面样式:(显示效果)

C# MVC(File)控件多张图片上传加预览

预览效果:(唯一的缺点就是上传的好像不是高清图片,是经过压缩的。目的是为了节省空间)

C# MVC(File)控件多张图片上传加预览

成功上传会有一个状态显示:

C# MVC(File)控件多张图片上传加预览

这样就已经完成图片上传啦!也保存在了本地!

接下来就看一下代码是如何实现的吧!

前端代码:

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Script/jquery-1.8.2.min.js"></script>
<link href="~/CSS/webuploader.css" rel="stylesheet" />
<script src="~/Script/webuploader.js"></script>
<link href="~/CSS/bootstrap.min.css" rel="stylesheet" />
<link href="~/CSS/style.css" rel="stylesheet" />
<link href="~/CSS/demo.css" rel="stylesheet" />
<link href="~/CSS/font-awesome.css" rel="stylesheet" /> </head>
<body>
<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> </body>
</html>

前端代码

这就没什么新颖的了,也无非就是一些前端的File控件的标签!

接下来就是页面的脚本代码了:

每一步的具体意思也都标有注释!

  1 <script type="text/javascript">
2
3 var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
4 $(function () {
5 var $ = jQuery,
6 $list = $('#fileList'),
7 // 优化retina, 在retina下这个值是2
8 ratio = window.devicePixelRatio || 1,
9 // 缩略图大小
10 thumbnailWidth = 90 * ratio,
11 thumbnailHeight = 90 * ratio,
12
13 // Web Uploader实例
14 uploader;
15 uploader = WebUploader.create({
16 // 选完文件后,是否自动上传。
17 auto: false,
18
19 disableGlobalDnd: true,
20 // swf文件路径
21 swf: applicationPath + '/Script/Uploader.swf',
22
23 // 文件接收服务端。
24 server: applicationPath + '/Home/UpLoadProcess',
25
26 // 选择文件的按钮。可选。
27 // 内部根据当前运行是创建,可能是input元素,也可能是flash.
28 pick: '#filePicker',
29
30 //只允许选择图片
31 accept: {
32 title: 'Images',
33 extensions: 'gif,jpg,jpeg,bmp,png',
34 mimeTypes: 'image/*'
35 }
36 });
37
38 // 当有文件添加进来的时候
39 uploader.on('fileQueued', function (file) {
40 var $li = $(
41 '<div id="' + file.id + '" class="cp_img">' +
42 '<img>' +
43 '<div class="cp_img_jian"></div></div>'
44 ),
45 $img = $li.find('img');
46
47
48 // $list为容器jQuery实例
49 $list.append($li);
50
51 // 创建缩略图
52 // 如果为非图片文件,可以不用调用此方法。
53 // thumbnailWidth x thumbnailHeight 为 100 x 100
54 uploader.makeThumb(file, function (error, src) {
55 if (error) {
56 $img.replaceWith('<span>不能预览</span>');
57 return;
58 }
59
60 $img.attr('src', src);
61 }, thumbnailWidth, thumbnailHeight);
62 });
63
64 // 文件上传过程中创建进度条实时显示。
65 uploader.on('uploadProgress', function (file, percentage) {
66 var $li = $('#' + file.id),
67 $percent = $li.find('.progress span');
68
69 // 避免重复创建
70 if (!$percent.length) {
71 $percent = $('<p class="progress"><span></span></p>')
72 .appendTo($li)
73 .find('span');
74 }
75
76 $percent.css('width', percentage * 100 + '%');
77 });
78
79 // 文件上传成功,给item添加成功class, 用样式标记上传成功。
80 uploader.on('uploadSuccess', function (file, response) {
81
82 $('#' + file.id).addClass('upload-state-done');
83 });
84
85 // 文件上传失败,显示上传出错。
86 uploader.on('uploadError', function (file) {
87 var $li = $('#' + file.id),
88 $error = $li.find('div.error');
89
90 // 避免重复创建
91 if (!$error.length) {
92 $error = $('<div class="error"></div>').appendTo($li);
93 }
94
95 $error.text('上传失败');
96 });
97
98 // 完成上传完了,成功或者失败,先删除进度条。
99 uploader.on('uploadComplete', function (file) {
100 $('#' + file.id).find('.progress').remove();
101 });
102
103 //所有文件上传完毕
104 uploader.on("uploadFinished", function ()
105 {
106 //提交表单
107
108 });
109
110 //开始上传
111 $("#ctlBtn").click(function () {
112 uploader.upload();
113
114 });
115
116 //显示删除按钮
117 $(".cp_img").live("mouseover", function ()
118 {
119 $(this).children(".cp_img_jian").css('display', 'block');
120
121 });
122 //隐藏删除按钮
123 $(".cp_img").live("mouseout", function () {
124 $(this).children(".cp_img_jian").css('display', 'none');
125
126 });
127 //执行删除方法
128 $list.on("click", ".cp_img_jian", function ()
129 {
130 var Id = $(this).parent().attr("id");
131 uploader.removeFile(uploader.getFile(Id,true));
132 $(this).parent().remove();
133 });
134
135 });
136
137
138 </script>

页面脚本

接下来就是后台控制器接收前台页面异步过来的数据了(代码如下):

 1  public class HomeController : Controller
2 {
3 static string urlPath = string.Empty;
4 public HomeController()
5 {
6 var applicationPath = VirtualPathUtility.ToAbsolute("~") == "/" ? "" : VirtualPathUtility.ToAbsolute("~");
7 urlPath = applicationPath + "/Upload";
8
9 }
10
11 public ActionResult Index()
12 {
13 return View();
14 }
15
16 public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
17 {
18 string filePathName = string.Empty;
19
20 string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload");
21 if (Request.Files.Count == 0)
22 {
23 return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
24 }
25
26 string ex = Path.GetExtension(file.FileName);
27 filePathName = Guid.NewGuid().ToString("N") + ex;
28 if (!System.IO.Directory.Exists(localPath))
29 {
30 System.IO.Directory.CreateDirectory(localPath);
31 }
32 file.SaveAs(Path.Combine(localPath, filePathName));
33
34 return Json(new
35 {
36 jsonrpc = "2.0",
37 id = id,
38 filePath = urlPath + "/" + filePathName
39 });
40
41 }
42
43 }

控制器接收代码

页面所引用到的脚本和CSS样式在这里(你可以根据最上面的HTML代码找到他所引用的脚本和CSS)

Script:

jquery-1.8.2.min.js  这是好像是一个专门对图片进行上传的脚本,你也可以去官网下载!

接下来还需要引用webuploader.js 这个脚本由于文件太大,我也不知道怎么上传文件。

CSS:

webuploader.css

 1 .webuploader-container {
2 position: relative;
3 }
4 .webuploader-element-invisible {
5 position: absolute !important;
6 clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
7 clip: rect(1px,1px,1px,1px);
8 }
9 .webuploader-pick {
10 position: relative;
11 display: inline-block;
12 cursor: pointer;
13
14 padding:0px;
15 width:100%;
16 height:100%;
17 color: #fff;
18 text-align: center;
19 border-radius: 3px;
20 overflow: hidden;
21 }
22 .webuploader-pick-hover {
23
24 }
25
26 .webuploader-pick-disable {
27 opacity: 0.6;
28 pointer-events:none;
29 }

bootstrap.min.css    内容太多,这个样式你可以去bootstrap官网下载

接下来还需要引用style.css 还是由于这个文件太大,我也不知道怎么上传文件。 

接下来还需要引用demo.css 还是由于这个文件太大,我也不知道怎么上传文件。 

接下来还需要引用font-awesome.css 还是由于这个文件太大,我也不知道怎么上传文件。 

由于不知道如何上传文件,就只能这样把代码一个一个的拷贝在界面上了。

还有这些页面上会用到的图片,我把它放在这里。你可以对应着style.css里面去把这里图片放在你项目的相应位置

C# MVC(File)控件多张图片上传加预览        C# MVC(File)控件多张图片上传加预览      C# MVC(File)控件多张图片上传加预览       C# MVC(File)控件多张图片上传加预览      C# MVC(File)控件多张图片上传加预览

这个代码实用性自我认为很强,有需要的朋友可以借鉴参考!

装载是希望您表明原文出处! 谢谢!

作者:奔奔