1. 程式人生 > >gif跨域請求成功返回圖片

gif跨域請求成功返回圖片

場景:統計前端資料,以image形式傳送請求以解決跨域問題,請求成功後返回一個小圖片。

前端

       
function doGet(){
    var url = 'http://127.0.0.1:8080/t.gif';
    var gif = new Image(1, 1);
    gif.src = url;
    gif.onload = function(){};
}  

後端(springboot)

/**
     * 返回圖片
     * @param response
     * 
     */
    public  void sentImg(HttpServletResponse response) {
        ServletOutputStream out = null;
        FileInputStream  fis = null;
         try {
             File path = new File(ResourceUtils.getURL("classpath:").getPath());
            // 圖片在專案中的路徑為 resources/static/images/img200.png
             File img = new File(path.getAbsolutePath(),"static/images/img200.png");
             fis = new FileInputStream(img);
             byte[] b = new byte[fis.available()];
             fis.read(b);
             response.setHeader("Pragma", "no-cache");
             response.setHeader("Cache-Control", "no-cache");
             response.setDateHeader("Expires", 0);
             response.setContentType("image/jpeg");
             out = response.getOutputStream();
             out.write(b);
         } catch (IOException e) {
             e.printStackTrace();
         }finally{
             try {
                 if(null != out)
                     out.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
             try {
                 if(null != fis)
                     fis.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
             
         }
    }