項目最開始用百度團隊的文件上傳組件作了個物料照片採集的功能,後來作員工頭像採集時居然不知道怎麼使用了。javascript
參照官方Demo:css
http://fex.baidu.com/webuploader/getting-started.htmlhtml
前端代碼:前端
@{ ViewBag.Title = "頭像採集"; Layout = "~/Views/P2Mobile/P2MB_LayoutPage.cshtml"; } <link href="~/Themes/P2Mobile/css/webuploader.css" rel="stylesheet" /> <script src="~/Themes/P2Mobile/js/webuploader.min.js"></script> <script src="~/Themes/Scripts/layui/layui.all.js"></script> <link href="~/Themes/Scripts/layui/css/layui.css" rel="stylesheet" /> <script type="text/javascript"> function DeleteImg(fileid) { //頁面層 //layer.open({ // type: 1 // , anim: 2 // , style: 'position:fixed; bottom:0; left:0; width: 100%; height: 40px; padding:10px 0; border:none;color:red;' // , shadeClose: true //開啓遮罩關閉 // //,skin: 'layui-layer-demo', //樣式類名 // ,closeBtn: 1 //顯示關閉按鈕 // , content: '<div class="row list-group"><div class="list-group-item font15" style="text-align:center" id="cp_img_jian" data-picid="' + fileid + '"><p style="display:inline-block;">刪除</p></div></div>' //}); layer.msg('你肯定你很帥麼?', { time: 0 //不自動關閉 , content: '<div class="row list-group" ><div class="list-group-item font15" style="text-align:center" id="cp_img_jian" data-picid="' + fileid + '"><p style="display:inline-block;">移除</p></div></div>' }); } $(document).ready(function () { $(document).on("click", "#cp_img_jian", function () { var pic = document.getElementById("cp_img_jian"); var Id = pic.getAttribute('data-picid'); uploader.removeFile(uploader.getFile(Id, true)); $('#' + Id).remove(); layer.closeAll(); }); var $list = $('#fileList'), // 優化retina, 在retina下這個值是2 ratio = window.devicePixelRatio || 1, // 縮略圖大小 thumbnailWidth = 400 * ratio, thumbnailHeight = 400 * ratio, serverURL = '/FRUBarCodeOtherMobile/FRU_UploadAvatarImages?JobNum=', uploader; // 初始化Web Uploader uploader = WebUploader.create({ // 自動上傳。 auto: false, // swf文件路徑 swf: '../../Themes/P2Mobile/js/Uploader.swf', // 文件接收服務端。 server: "/FRUBarCodeOtherMobile/FRU_UploadAvatarImages", // 選擇文件的按鈕。可選。 // 內部根據當前運行是建立,多是input元素,也多是flash. pick: '#filePicker', fileNumLimit: 1,//限制上傳最多10張圖片 // 不壓縮image, 默認若是是jpeg,文件上傳前會壓縮一把再上傳! accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }); // 當有文件添加進來的時候 uploader.on('fileQueued', function (file) { var $li = $( '<div id="' + file.id + '" class="file-item thumbnail" onclick="DeleteImg(\'' + file.id + '\')">' + '<img>' + '<div class="info">' + file.name + '</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'); }); // 文件上傳失敗,顯示上傳出錯。 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 () { var ststs = uploader.getStats(); //提交表單 alert("成功上傳" + ststs.successNum + "張圖片。"); window.location.reload();//刷新頁面 }); //執行上傳 $("#ctlBtn").click(function () { var str_JobNum = $("#txt_str_JobNum").val(); if (str_JobNum.replace(/(^s*)|(s*$)/g, "").length == 0) { layer.alert('提交前請輸入員工工號哦!', { icon: 6 }); } else { uploader.options.formData.JobNum = str_JobNum; uploader.upload(); } }); //掃描框驗證 $("#txt_scanarea").focus(); $("#txt_scanarea").focus(function () { this.select(); }); //掃描框enter驗證 $("#txt_scanarea").keydown(function (e) { var scantext = $("#txt_scanarea").val();//獲取掃描內容 var keyCode = e.which; if (keyCode == 13 || keyCode == 115) { if (scantext) { $.ajax({ url: "/FRUBarCodeOtherMobile/FRU_UploadScanCheckJobNum", type: "post", data: { 'ScanText': scantext }, datatype: "json", success: function (data) { //掃描成功 if (data.msgType == "success") { if (data.type == "ScanJobNumSuccess") { $("#txt_scanarea").val(""); $("#txt_str_JobNum").val(data.JobNum); } $("#txt_scanarea").focus(); } //掃描失敗 if (data.msgType == "error") { layer.open({ content: data.msg, skin: 'msg', time: 3 }); $("#txt_scanarea").focus(); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { layer.open({ content: '鏈接已超時' , skin: 'msg' , time: 3 //3秒後自動關閉 }); } else { layer.open({ content: '服務器錯誤,請聯繫管理員' , skin: 'msg' , time: 3 //3秒後自動關閉 }); } } }) } else { layer.open({ content: '掃描區域不能爲空' , skin: 'msg' , time: 2 //3秒後自動關閉 }); $("#txt_scanarea").focus(); } } }); }) </script> <div style="padding: 5px;"> <div class="row" style="margin-bottom: 5px;"> <div class="col-xs-3" style="padding: 0; line-height: 34px; font-size: 1em"> <label style="margin-left: 10px;"> 掃描區域: </label> </div> <div class="col-xs-9" style="padding: 0;"> <input type="text" class="form-control" id="txt_scanarea" name="txt_scanarea" style="background-color: #f8ac59" /> </div> </div> <div class="row" style="margin-bottom: 5px;"> <div class="col-xs-3" style="padding: 0; line-height: 34px; font-size: 1em"> <label style="margin-left: 10px;"> 員工工號: </label> </div> <div class="col-xs-9" style="padding: 0;"> <input type="text" class="form-control" id="txt_str_JobNum" name="txt_str_JobNum" readonly /> </div> </div> </div> <div id="uploader" class="wu-example"> <!--用來存放文件信息--> <div id="fileList" class="uploader-list"></div> <div class="btns"> <div id="filePicker">選擇文件</div> <button id="ctlBtn" class="btn btn-default">開始上傳</button> </div> </div>
在點擊了選擇文件後,建立縮略圖並追加上去java
後臺處理web
public ActionResult FRU_UploadAvatarImages(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file, string JobNum) { LogHelper lh = new LogHelper(); if (user != null) { DBConn = user.DBConn.ToString(); } else { return RedirectToAction("Login", "P2Mobile"); } try { string str_JobNum = ""; str_JobNum = JobNum; string filePathName = string.Empty; string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "AvatarPhotos"); localPath = Path.Combine(localPath, str_JobNum); 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)); //插日誌 string UrlLog = Path.Combine("AvatarPhotos", str_JobNum, filePathName); P2Mobile_InventoryBarCodeiBLL.ExecSql(string.Format(@" INSERT INTO dbo.WMS_AvatarPhotos ( Account, PhotoName, Url, CreateBy ) VALUES ( '{0}', '{1}', '{2}', '{3}' )", str_JobNum, filePathName, UrlLog, user.Account), DBConn); return Json(new { jsonrpc = "2.0", id = id, filePath = "/Upload/" + filePathName }); } catch (Exception e) { lh.WriteLog(e.ToString() + "\n+-+-+-+-+-+-+-+-+-+-+-+-+操做人【" + user.Account + "】+-+-+-+-+-+-+-+-+-+-+-+-+"); return Json(new { msgType = JsonMsgType.Error, msg = e.ToString() }); } }