SpringMVC+jsp根據圖片地址url加載服務器端的圖片顯示到頁面中

html代碼

<head>
	<script type="text/javascript">

	$(document).ready(function(){
		$(function() {
			// 圖片初始化
			// 例如:myUrl = "D:/a/a1/圖片目錄/20191018/20191018163841.jpg,D:/a/a1/圖片目錄/20191019/20191018163843.jpg";
			var myUrl = "${obj.imgUrl}";
			if (myUrl != null && myUrl.length != 0) {
				var myImgBox = $("#imgDIV .review-box");
				var imgList = myUrl.split(",");
				for (var i = 0; i < imgList.length; i++) {
					var imgUrl = imgList[i];
					if (imgUrl.length != 0) {
						var img = $("<img src='${url }/showImage.do?img=" + imgUrl + "'>");
						var imgbox = $("<div class='prev-item'></div>");
						imgbox.append(img);
						imgbox.append("<input name='showImgUrl' type='hidden' value='"+imgUrl+"'>");
						myImgBox.append(imgbox);
					}
				}
			}
		});
	});
	</script>
</head>
<body>

	<div class="" id="imgDIV">
		<div class="review-box">
		</div>
	<div>

</body>

java代碼

/**
 * 根據圖片url加載圖片
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/showImage")
public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception {

	InputStream inputStream = null;
	OutputStream writer = null;
	try {
		inputStream = new FileInputStream(new File(request.getParameter("img")));
		writer = response.getOutputStream();

		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = inputStream.read(buf)) != -1) {
			writer.write(buf, 0, len); 
		}
		inputStream.close();
	} catch (Exception e) {
		this.logException(e);
	} finally {
		try {
			if (inputStream != null) {
				inputStream.close();
			}
			if (writer != null) {
				writer.close();
			}
		} catch (IOException e) {
			this.logException(e);
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章