如何在jsp中显示图像?

我有一个bytearray图像。

我需要在jsp页面中以jpg格式显示该图像,并且在单击图像时,我可以将图像下载到我的电脑:

我从我的mysql数据库加载图像作为字节数组..

我的代码是

ResultSet res = statement.executeQuery("SELECT * FROM upload_data where user_id = "+userID); while (res.next()) { contactDetails = new ContactDetails(); contactDetails.setContactPhoto(res.getBytes("photo")); byteArrayBackToImage1(res.getBytes("photo")); contactsList.add(contactDetails); } public void byteArrayBackToImage1(byte[] imageInByte){ try{ Random rand = new Random(); int numNoRange = rand.nextInt(); String number = String.valueOf(numNoRange); //convert byte array back to BufferedImage InputStream in = new ByteArrayInputStream(imageInByte); BufferedImage bImageFromConvert = ImageIO.read(in); System.out.println("bImageFromConvert : "+bImageFromConvert); /*ImageIO.write(bImageFromConvert, "jpg", new File("c:\\"+number+".jpg")); */ }catch (Exception e) { // TODO: handle exception } 

我需要在jsp中显示图像

例如:image.jpg image2.jpg

通过单击image.jsp,我可以下载该图像并将其保存到我的电脑

请帮忙

您在JSP中生成的HTML必须包含一个img元素,其中src指向servlet或action的URL,该URL将从数据库加载图像并将其发送到具有image / jpeg内容类型的输出流。

 // in your HTML :  // in the servlet mapped to /getImage.action: // get the ID of the image from the request parameters String imageId = request.getParameter("imageId"); byte[] imageData = getImageFromDatabase(imageId); response.setContentType("image/jpeg"); response.getOutputStream().write(imageData); 

所有浏览器都右键单击 – 将图像另存为…菜单项,因此我不会在应用程序中实现此function。

JSP:

 
" width="117" height="160" onError="loadImage()" onAbort="loadImage()" />

Servlet // imageDisplayProcess

 imgByt = imageClass.getPhotograph();//return blob... response.setContentType("image/jpg"); response.getOutputStream().write(imgByt); response.getOutputStream().flush(); response.getOutputStream().close();