【我要编程】Java技术手册之根据图片链接把图片转化为io流,并输出到页面上的方法

适用场景:A程序只能内网访问,B程序可以外网访问,只有B程序可以访问A程序,用户需要通过B程序访问A程序的图片资源。这是可以使用该方法。

@RequestMapping("/getImageByPath")

public void getImageByTomcat(String path,String suffix,HttpServletResponse response) {

OutputStream os=null;

try {

//这里需要一个最终能在服务器浏览器只能访问图片的地址

String strUrl = "http://ip地址/image/"+path;

URL url = new URL(strUrl );

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.setRequestMethod("GET");

conn.setConnectTimeout(5 * 1000);

InputStream inputStream = conn.getInputStream();//通过输入流获取图片数据

os = response.getOutputStream();

int count = 0;

byte[] buffer = new byte[1024 * 8];

while ((count = inputStream.read(buffer)) != -1) {

os.write(buffer, 0, count);

os.flush();

}

inputStream.close();

//设置发送到客户端的响应内容类型  

 

 if (path.toLowerCase().endsWith("jpg"))

 {

   response.setContentType("image/jpg");

 }

 else if (path.toLowerCase().endsWith("jpeg"))

 {

   response.setContentType("image/jpeg");

 }

 else if (path.toLowerCase().endsWith("gif"))

 {

   response.setContentType("image/gif");

 }

 else if (path.toLowerCase().endsWith("png"))

 {

   response.setContentType("image/png");

 }

 else if (path.toLowerCase().endsWith("bmp"))

 {

   response.setContentType("image/bmp");

 }else if (path.toLowerCase().endsWith("mp3"))

 {

   response.setContentType("audio/mpeg");

 }

os = response.getOutputStream();

} catch (Exception e) {

e.printStackTrace();

}finally {

if(null != os){

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

 

本文整理于“我要编程”免费Java课程之学习笔记

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值