ajax接收後臺傳來的圖片
阿新 • • 發佈:2018-11-12
ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流 ImageIO.write(png, "png", baos);//寫入流中 byte[] bytes = baos.toByteArray();//轉換成位元組 BASE64Encoder encoder = new BASE64Encoder(); String png_base64 = encoder.encodeBuffer(bytes);//轉換成base64串 png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//刪除 \r\n return png_base64;
ajax接收後臺圖片
後臺
/** * #獲取驗證碼的圖片 * #使用點選事件獲取驗證碼圖片 */ @SuppressWarnings("unused") private void checkcodeImgClick(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //點選圖片按鍵請求 DrowPictureUtils pic = DrowPictureUtils.getDrawPicUtils(); pic.set(65, 37); String checkCode = pic.generateCheckCode();//獲取隨機驗證碼 BufferedImage image = pic.generateCheckImage(checkCode); req.getSession().setAttribute("checkcode", checkCode);//session需要記錄該驗證碼 //點選其他按鍵請求 ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流 ImageIO.write(image, "png", baos);//寫入流中 byte[] bytes = baos.toByteArray();//轉換成位元組 BASE64Encoder encoder = new BASE64Encoder(); String png_base64 = encoder.encodeBuffer(bytes);//轉換成base64串 png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//刪除 \r\n resp.getWriter().write(png_base64); }
前臺
/** * 申請更新驗證碼 * 該請求不需要有任何引數 */ $("#checkcodeImg").click(function() { $.ajax({ type: "post", url: "./checkcodeImgClick.reg", dataType: "text", success: function(img, status){ alert(img); $("#checkImg").attr("src","data:image/png;base64,"+img); }, error:function(data){ alert('響應失敗!'); }, }); });