适用场景: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();
}
}
}
}
免费学习编程:www.51program.com
全套Java课程免费分享请关注微信公众号:我要编程(微信号:oset51)
技术交流群:259657781