js+java 實現圖片線上預覽功能
阿新 • • 發佈:2019-02-08
本部落格主要描述如何用JavaScript+java實現圖片的預覽功能,其實要點還是需要服務端的流。
(一)功能描述
點選頁面的 【預覽】 檢視已經上傳的或者在伺服器中存在的圖片。
(二)實現原理
使用img標籤的src屬性來渲染資料,但是,src的值是服務端返回的檔案流。即是,點選【預覽】按鈕,跳轉到預覽頁面,預覽頁面的img標籤的src屬性的值是經過渲染的檔案流。
(三)具體的實現程式碼
- (1)【預覽】按鈕頁,需要傳從服務端傳來的路徑
<html>
<button id="yulanButton">預覽</button>
<script type="text/javascript">
$(function(){
$("#yulanButton").on('click', function(){
// 開啟預覽頁面,需要傳伺服器的路徑(url傳值,可參考我的另一篇部落格《js url傳參》)
window.open('./yulan.jsp?url=獲取到的伺服器的路徑');
})
})
})
</script>
</html>
- (2) yulan.jsp 預覽頁面,需要連線到獲取圖片留的jsp
<div class="imgdiv">
<img id="imgss" src="../params/projAndDetailImg.jsp" title="線上預覽">
</div>
<script type="text/javascript">
var yulanUrl = 獲取到的伺服器的路徑
$(function(){
$("#imgss").attr('src', "../params/projAndDetailImg.jsp?photoUrl=" +yulanUrl)
});
</script>
- (3) projAndDetailImg.jsp 服務端渲染頁面
<%
String photoUrl=request.getParameter("photoUrl");
// photoUrl為接收到的路徑
if(StringUtils.isNotBlank(photoUrl)){
File file = new File(photoUrl);
// File file=new File(photoUrl);
if (file.exists()) {
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis, 1024);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);) {
byte[] cache = new byte[1024];
int length = 0;
while ((length = bis.read(cache)) != -1) {
bos.write(cache, 0, length);
}
/**
return bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bos.toByteArray());
**/
response.getOutputStream().write(bos.toByteArray());
}
}
}
%>
ok !!!
圖片在先預覽功能相對於前端來說,不是有多複雜,只需要一個img標籤即可,但是需要我們在jsp頁面經過<%%>服務端渲染出一個檔案路徑流,方能訪問到該圖片地址。
方法,千千萬,這只是其一。
https://github.com/mcya/JavaScriptExperience/issues