剛來公司實習,老板叫我寫一個積分商城網站。用的是公司的框架結構搭建的后台,所以后台的圖片上傳不需要自己寫。但是前台的評價圖片就需要自己手寫了,在網上找了很多代碼發現都用不了。問了很多人也都沒有實現!
最后公司同事給我了一個上傳的代碼,拿來借用。發現效果很好,困擾了我很多天的問題,也得於解決。現在我把他分享出來!
先看一下上傳效果:
界面樣式:(顯示效果)
預覽效果:(唯一的缺點就是上傳的好像不是高清圖片,是經過壓縮的。目的是為了節省空間)
成功上傳會有一個狀態顯示:
這樣就已經完成圖片上傳啦!也保存在了本地!
接下來就看一下代碼是如何實現的吧!
前端代碼:

<!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里面去把這里圖片放在你項目的相應位置
這個代碼實用性自我認為很強,有需要的朋友可以借鑒參考!
裝載是希望您表明原文出處! 謝謝!
作者:奔奔