简述:
实现用HTTP连接获取一张图片,在servlet中转为流之后输出,这样访问一个service之后就能直接得到图片流并显示出来
类似于访问一个图片的src(html)中会向一个http://localhost:8080/webproj/i.jpg发送请求,于是浏览器就会显示这张图片出来,现在要实现一个后台的service,做的是同样的事情但是请求的却是service,而这个service就返回了图片流回来
代码:
/**
* 获取图片
* @param request
* @param response
*/
public void GetImage(HttpServletRequest request
, HttpServletResponse response){
try {
URL url = new URL("http://csdnimg.cn/www/images/csdnindex_logo.gif");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
byte data[] = readInputStream(inStream);
inStream.read(data); //读数据
inStream.close();
response.setContentType("image/jpg"); //设置返回的文件类型
OutputStream os = response.getOutputStream();
os.write(data);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
/**
* 上传首页图片
* @param request
* @param response
*/
public void UploadHomeImage(HttpServletRequest request
, HttpServletResponse response){
//存储文件,同时获取表单中的输入值对
Map<String, String> nameValuePair = new HashMap<String, String>();
//户型图片存储对象
HomeImage homeImage = new HomeImage();
//获取存储的地址,同时捕获参数值对
String imageUrl = saveUploadFile(request, "/Upload/HomeImage/", nameValuePair);
homeImage.setImageUrl(imageUrl);
homeImage.setUploadDate(new Date());
settingService.saveOrUpdateHomeImage(homeImage);
//获取信息界面显示类
HomeImagePage responsePage = settingService.getWebHomePage();
//将页面显示数据类转化为JSON,返回前端
responseOutWithJson(response, responsePage);
response.setStatus(HttpServletResponse.SC_OK);
}