写项目的时候写的,感觉以后还会用,所以记录一下
一种通过 java 的get请求获取 网上图片的数据
二种,通过获取本地的具体文件下的图片的数据
前台写的
date.t.avatat 是 存在数据库中 图片的地址
一种是本地地址
一种是 http地址
后台
@RequestMapping("getImagesByAll")
@ResponseBody
public void getImagesByAll(HttpServletResponse response, String picture){
response.setContentType("image/jpeg;charset=utf-8");
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
if(!picture.startsWith("./")){
try{
URL url = new URL(picture);
HttpURLConnection urlCon= (HttpURLConnection)url.openConnection();
if(200==urlCon.getResponseCode()){
InputStream is = urlCon.getInputStream();
byte[] buffer = new byte[1024];
int len =0;
while(( len = is.read(buffer)) >0 ){
outputStream.write(buffer,0,len);
}
outputStream.close();
is.close();
}
}catch(Exception e){
e.printStackTrace();
}
}else{
String pictureName = picture.split("/")[2];
System.out.println(picture);
String pictureAddress = "D:\\idea\\MyBlog\\src\\main\\resources\\static\\images\\"+pictureName;
System.out.println(pictureAddress);
try {
FileInputStream fis = new FileInputStream(pictureAddress);
byte[] buffer = new byte[1024];
int len = 0 ;
while( (len = fis.read(buffer)) > 0 ){
outputStream.write(buffer,0,len);
}
fis.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}