jsp中點擊圖片彈出檔案上傳介面及預覽功能的實現_JSP編程

來源:互聯網
上載者:User
花了兩天時間琢磨一下圖片預覽的功能

任務需求如下:

1:jsp頁面中有一個圖片(pic_1)
2:點擊圖片彈出類似於資源管理員的介面
3:選擇完某一個圖片之後在pic_1處預覽

我在IE8上實驗下面這段代碼,可以實現上述功能,沒有在別的瀏覽器中測試,如果各位朋友知道多種瀏覽器的支援方法,請賜教,共同學習,謝謝。
複製代碼 代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript">
function tempClick(){

/**
* Firefox瀏覽器實現點擊圖片出現檔案上傳介面
* var a=document.createEvent("MouseEvents");
* a.initEvent("click", true, true);
* document.getElementById("upload_main_img").dispatchEvent(a);
*/

//IE瀏覽器實現點擊圖片出現檔案上傳介面
document.getElementById('main_img').click(); //調用main_img的onclick事件
}

/**
* 預覽圖片
* @param obj
* @returns {Boolean}
*/
function PreviewImg(obj) {

var newPreview = document.getElementById("img_2");
var imgPath = getPath(obj);
alert(imgPath);
if( !obj.value.match( /.jpg|.gif|.png|.bmp/i ) ){
alert("圖片格式錯誤!");
return false;
}

newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
newPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgPath;
}

/**
* 得到圖片絕對路徑
* @param obj
* @returns
*/
function getPath(obj){
if(obj) {
if(navigator.userAgent.indexOf("MSIE")>0) {
obj.select();
//IE下取得圖片的本地路徑
return document.selection.createRange().text;
} else if(isFirefox=navigator.userAgent.indexOf("Firefox")>0) {
if (obj.files) { // Firefox下取得的是圖片的資料
return files.item(0).getAsDataURL();
}
return obj.value;
}
return obj.value;
}
}
</script>
</head>
<body>
<form>
<div><input type="file" style="position: absolute; filter: alpha(opacity = 0); opacity: 0; width: 30px;" size="1" id="main_img" name="main_img" onchange="PreviewImg(this)"></div>
<div id="img_2" style="width:133px;height:95px; cursor:pointer; background-image: url('Chrysanthemum.jpg');" onclick="tempClick()"></div>
</form>
</body>
</html>

簡單的對代碼做一下講解:
input type="file" 這個元素我試過讓style隱藏(style=“display:none”),這樣就不能或得到絕對路徑,而是fakepath,為了不讓它顯示出來就讓他100%的透明,下面有一個div,id為img_2,這個div是頁面初始圖片,點擊這個圖片調用input type="file" 中的方法,實現此功能。 

能力有限,還請各位指教,有更好的方法請提供給我,共同學習,Thanks。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.