springMVC 返迴流圖片顯示,前端接受流

  • 2019 年 11 月 7 日
  • 筆記

後端程式碼:

	@RequestMapping(value = "read")  	public void index(Model model, HttpServletRequest req,  			HttpServletResponse resp, String attachmentId) {  			byte [] bytes = null;  			 ServletOutputStream sos =null;// 將影像輸出到Servlet輸出流中。  		try {              GetImageRes getImageRes = acctManager.getImageBytes(attachmentId);  			bytes = getImageRes.getFilebyte();    			ByteArrayInputStream in = new ByteArrayInputStream(bytes);    //將b作為輸入流;  			BufferedImage image = ImageIO.read(in);    			 resp.setHeader("Pragma", "no-cache");  			 resp.setHeader("Cache-Control", "no-cache");  			 resp.setDateHeader("Expires", 0);               sos = resp.getOutputStream();// 將影像輸出到Servlet輸出流中。               ImageIO.write(image, "jpeg", sos);            } catch (IOException e) {                e.printStackTrace();          } finally {                try {  				sos.close();  			} catch (IOException e) {  				e.printStackTrace();  			}          }  	}

直接訪問springmvc路徑 直接訪問通過流的形式返回圖片,但是這個有一個缺陷就是 返回的title是路徑名稱加像素。

為了解決這種問題 從前端改接受流的方式完成。

前端程式碼:

<html>  	<head>  		<meta name="viewport" content="width=device-width, minimum-scale=0.1">  		<title>圖片</title>  	</head>  <body  style="margin: 0px;">    	<img  id="tempImage" style="-webkit-user-select: none;cursor: zoom-in;" src="$!imgUrl" width="100%" height="100%">    </body>  </html>

後端程式碼:

@RequestMapping(value = "readHtml")  	public String readHtml(Model model, HttpServletRequest req,  			HttpServletResponse resp, String attachmentId,String recommendId) {    		model.addAttribute("imgUrl", "這裡直接寫上訪問流路徑");    		return "tempImage/tempImage";  	}

這裡就完成了 。