简述:
将本地一张本地的图片转为流之后返回
代码:
/**
* 获取图片
* @param request
* @param response
*/
public void GetHomeImage(HttpServletRequest request
, HttpServletResponse response){
//获取首页图片显示类
String filePath = "D://img.jpg";
try {
byte data[] = readFile(filePath);
response.setContentType("image/jpg"); //设置返回的文件类型
OutputStream os = response.getOutputStream();
os.write(data);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从文件地址,读取文件的Byte数组
* @param filename
* @return
* @throws IOException
*/
public static byte[] readFile(String filename) throws IOException {
if( filename==null || filename.equals("") ){
throw new NullPointerException("无效的文件路径");
}
File file =new File(filename);
long len = file.length();
byte[] bytes = new byte[(int)len];
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
int r = bufferedInputStream.read( bytes );
if (r != len)
throw new IOException("读取文件不正确");
bufferedInputStream.close();
return bytes;
}
这样通过访问server的service就直接能得到图片了
http://192.168.2.199:8087/MyProject/TestService?action=GetHomeImage