java中上傳圖片,加載上傳的圖片到頁面

在java中實現圖片的上傳,並且顯示圖片到頁面的功能分爲以下幾步:

1、上傳圖片代碼(此處是讀取圖片,轉換爲流,寫入數據庫中保存)

		FileInputStream fis = new FileInputStream("d:/test/2.jpg");
		//此處是mysql數據庫驅動
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://192.168.67.19/xkxtbeta";
		//配置鏈接字符串,用戶名和密碼
		Connection connection = DriverManager.getConnection(url, "root", "123");
		//sql語句的生成採用參數注入的方式,且img字段的類型是BLOB類型
		String sql = "insert into image (id,img) values(?,?)";
		PreparedStatement statement = connection.prepareStatement(sql);
		statement.setInt(1, 2);
		statement.setBinaryStream(2, fis);
		statement.execute();
		connection.close();

2、從數據庫中讀取圖片的二進制流,寫入response中,代碼如下:

	@RequestMapping(value = "showimg.do", method = RequestMethod.GET)
	public void showImg(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws Exception {
		Integer id = Integer.valueOf(request.getParameter("id"));
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://192.168.67.19/xkxtbeta";
		Connection conn = DriverManager.getConnection(url, "root", "typ");

		String sql = "select img from image where id="+id;
		Statement sm = conn.createStatement();
		ResultSet rs = sm.executeQuery(sql);
		byte[] b = null;
		if (rs.next()) {
			b = rs.getBytes(1);
		}
		OutputStream os = response.getOutputStream();
		os.write(b);
		conn.close();
	}

3、jsp頁面代碼,在jsp頁面上面輸出

此處是img的src訪問第二步定義的showimg.do即可

<!DOCTYPE html>
<html>
	<head>
	<script src="resources/js/jquery.js"></script>
	<script type="text/javascript">
	</script>
	</head>

	<body>
		<div>
			<input type="text"/>
			<img src="showimg.do?id=1"></img>
			<img src="showimg.do?id=2" style="width:60px;height:60px"></img>
			<input type="button" value="submit" />
		</div>
	</body>
</html>
該程序的結果就是根據jsp傳回的id值,顯示數據庫中存儲的兩張不同的照片到jsp頁面上。

發佈了45 篇原創文章 · 獲贊 21 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章