頁面部分:javascript
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- </head>
- <body>
- <div>
- <input type="file" name="upfile" id="upfile" onchange="imgPreObj.changeFiles(this)"/>
- <div id="preview"><img src="" id="imgPre"></div>
- </div>
- </body>
- </html>
javascript代碼:html
- /**
- * @title 兼容多瀏覽器的圖片上傳預覽
- * @support IE6+,Firefox,Opera,Chrome
- * @author gaorunqiao / goen88@163.com
- * @version g.f.i.p0.0.0.02
- * @date 2012/08/31
- */
- //圖片上傳預覽
- function FILE_IMG_PREVIEW(imgID){
- this.fileObj = {}; //input file對象
- this.imgID = imgID; //輸出圖片對象ID
- this.formatFilter = ".jpg;.png;.gif;.bmp;";
- }
- //文件選取完成回調
- FILE_IMG_PREVIEW.prototype.changeFiles = function(obj){
- this.fileObj = obj;
- var oImgID = this.imgID; //輸出圖片ID
- if(this.checkFormat()==false) return; //文件格式檢測
- if(typeof FileReader != 'undefined'){ //支持html5讀取文件URL
- var files = this.fileObj.files;
- if(files.length>0){
- var reader = new FileReader();
- reader.onloadend = function(e) {
- document.getElementById(oImgID).src= this.result;
- }
- reader.readAsDataURL(files[0]);
- }
- }else{
- document.getElementById(oImgID).src = this.getPath();
- }
- }
- //獲取本地文件路徑
- FILE_IMG_PREVIEW.prototype.getPath = function(){
- if (this.fileObj) {
- //取得IE下本地圖片路徑
- if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
- this.fileObj.select();
- this.fileObj.blur();
- // IE下取得圖片的本地路徑
- return document.selection.createRange().text;
- }
- //firefox
- else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
- if (this.fileObj.files) {
- // Firefox下取得的是圖片的數據
- return this.fileObj.files.item(0).getAsDataURL();
- }
- return this.fileObj.value;
- }
- return this.fileObj.value;
- }else{
- return '';
- }
- }
- //檢測上傳文件的格式
- FILE_IMG_PREVIEW.prototype.checkFormat = function(){
- var upfile = this.fileObj.value;
- var format = upfile.substr(upfile.lastIndexOf('.')).toLowerCase();
- if(this.formatFilter.indexOf(format)!=-1){
- return true;
- }else{
- alert('錯誤:文件格式不正確,只支持'+this.formatFilter);
- return false;
- }
- }