首先下載源碼javascript
文件名 jquery.uploadView.js(注意前後順序,jquery必需要在插件以前引入)css
// 圖片上傳前預覽插件 //Power By 勾國印 //QQ:245629560 //Blog:http://www.gouguoyin.cn (function($){ $.fn.uploadView = function(options){ var defaults = { uploadBox: '.js_uploadBox', //設置上傳框容器 showBox : '.js_showBox', //設置顯示預覽圖片的容器 /*width : 200, //設置預覽圖片的寬度*/ height: 240, //設置預覽圖片的高度 allowType: ["gif", "jpeg", "jpg", "bmp", "png"], maxSize: 1, //設置容許上傳圖片的最大尺寸,單位M success:$.noop //上傳成功時的回調函數 }; var config = $.extend(defaults, options); var showBox = config.showBox; var uploadBox = config.uploadBox; var width = config.width; var height = config.height; var allowType = config.allowType; var maxSize = config.maxSize; var success = config.success; $(this).each(function(i){ $(this).change(function(e){ handleFileSelect($(this), width, height, allowType, maxSize, success); }); }); var handleFileSelect = function(obj, _w, _h, _type, _size, _callback){ if (typeof FileReader == "undefined") { return false; } var thisClosest = obj.closest(uploadBox); if (typeof thisClosest.length == "undefined") { return; } var files = obj[0].files; var f = files[0]; if (!isAllowFile(f.name, _type)) { alert("圖片類型必須是" + _type.join(",") + "中的一種"); return false; } var fileSize = f.size; var maxSize = _size*1024*1024; if(fileSize > maxSize){ alert('上傳圖片超出容許上傳大小'); return false; } var reader = new FileReader(); reader.onload = (function(theFile){ return function (e) { var tmpSrc = e.target.result; if (tmpSrc.lastIndexOf('data:base64') != -1) { tmpSrc = tmpSrc.replace('data:base64', 'data:image/jpeg;base64'); } else if (tmpSrc.lastIndexOf('data:,') != -1) { tmpSrc = tmpSrc.replace('data:,', 'data:image/jpeg;base64,'); } var img = '<img src="' + tmpSrc + '"/>'; //consoleLog(reader, img); thisClosest.find(showBox).show().html(img); if (_w && _h) { cssObj = { 'width':_w+'px', 'height':_h+'px' }; } else if (_w) { cssObj = { 'width':_w+'px' }; } else if (_h) { cssObj = { 'height':_h+'px' }; } else { cssObj = { 'max-width':'100%', 'max-height':'100%' }; } thisClosest.find(showBox+" img").css( cssObj ); _callback(); }; })(f) reader.readAsDataURL(f); } //獲取上傳文件的後綴名 var getFileExt = function(fileName){ if (!fileName) { return ''; } var _index = fileName.lastIndexOf('.'); if (_index < 1) { return ''; } return fileName.substr(_index+1); }; //是不是容許上傳文件格式 var isAllowFile = function(fileName, allowType){ var fileExt = getFileExt(fileName).toLowerCase(); if (!allowType) { allowType = ['jpg', 'jpeg', 'png', 'gif', 'bmp']; } if ($.inArray(fileExt, allowType) != -1) { return true; } return false; } }; })(jQuery); jQuery.extend({ unselectContents: function(){ if(window.getSelection) window.getSelection().removeAllRanges(); else if(document.selection) document.selection.empty(); } }); jQuery.fn.extend({ selectContents: function(){ $(this).each(function(i){ var node = this; var selection, range, doc, win; if ((doc = node.ownerDocument) && (win = doc.defaultView) && typeof win.getSelection != 'undefined' && typeof doc.createRange != 'undefined' && (selection = window.getSelection()) && typeof selection.removeAllRanges != 'undefined'){ range = doc.createRange(); range.selectNode(node); if(i == 0){ selection.removeAllRanges(); } selection.addRange(range); } else if (document.body && typeof document.body.createTextRange != 'undefined' && (range = document.body.createTextRange())){ range.moveToElementText(node); range.select(); } }); }, setCaret: function(){ if(!$.browser.msie) return; var initSetCaret = function(){ var textObj = $(this).get(0); textObj.caretPos = document.selection.createRange().duplicate(); }; $(this).click(initSetCaret).select(initSetCaret).keyup(initSetCaret); }, insertAtCaret: function(textFeildValue){ var textObj = $(this).get(0); if(document.all && textObj.createTextRange && textObj.caretPos){ var caretPos=textObj.caretPos; caretPos.text = caretPos.text.charAt(caretPos.text.length-1) == '' ? textFeildValue+'' : textFeildValue; } else if(textObj.setSelectionRange){ var rangeStart=textObj.selectionStart; var rangeEnd=textObj.selectionEnd; var tempStr1=textObj.value.substring(0,rangeStart); var tempStr2=textObj.value.substring(rangeEnd); textObj.value=tempStr1+textFeildValue+tempStr2; textObj.focus(); var len=textFeildValue.length; textObj.setSelectionRange(rangeStart+len,rangeStart+len); textObj.blur(); }else{ textObj.value+=textFeildValue; } } });
在模板頁加入上傳框,html: html
<div class="control-group js_uploadBox"> <div class="btn-upload"> <a href="javascript:void(0);"><i class="icon-upload"></i><span class="js_uploadText">上傳</span>圖片</a> <input class="js_upFile" type="file" name="cover" id="btnimages"> </div> <div class="js_showBox "><img class="js_logoBox" src="" width="100px" ></div> </div>
js:java
$(".js_upFile").uploadView({ uploadBox: '.js_uploadBox',//設置上傳框容器 showBox : '.js_showBox',//設置顯示預覽圖片的容器 width : 100, //預覽圖片的寬度,單位px height : 100, //預覽圖片的高度,單位px allowType: ["gif", "jpeg", "jpg", "bmp", "png"], //容許上傳圖片的類型 maxSize :2, //容許上傳圖片的最大尺寸,單位M success:function(e){ $(".js_uploadText").text('更改'); alert('圖片上傳成功'); } });
ajax請求要傳的參數之一:var docFile=document.getElementById("btnimages").files[0];node
通常的使用:jquery
1.用一些鍵值對來模擬一系列表單控件:即把form中全部表單元素的name與value組裝成 一個queryString 2. 異步上傳二進制文件。
//圖片上傳接口 function addImages(){ var docFile=document.getElementById("btnimages").files[0]; var doctorId=$("#usersnumber").val(); var formData=new FormData(); //上傳formdata封裝的數據 formData.append("myFile",docFile); formData.append("doctorId",doctorId); $.ajax({ url:"http://localhost:8080/doctormanage/file/updoctorphoto.do", type:"post", data:formData, cache:false, processData:false, contentType:false, success:function(result){ if(result.state==0){ alert("圖片上傳成功"); }else{ alert("圖片上傳失敗"); } } }); };
獲取圖片名稱:ajax
//圖片獲取名 function imgSear(){ var str; $('#btnimages').change(function(){//點擊選擇修改圖片時 str=$(this).val(); var arr=str.split('\\'); var my=arr[arr.length-1]; $("#choiceimages").val(my); }); }