java下载内网图片给前端



@PostMapping("/view")
public ApiResponse view(@RequestBody JSONObject json, HttpServletRequest request,HttpServletResponse response) throws Exception {
String userId = getUserId(request);
if (StringUtils.isEmpty(userId)) {
return ResponseCode.response(ResponseCode.token_error);
}

//获取到上传的文件数据
Object imgUrlObj = json.get("imgUrl");
if (imgUrlObj == null) {
return new ApiResponse(ResponseCode.parameter_error.getCode(), "imgUrl不能为空");
}

String url = imgUrlObj.toString();
BufferedImage img = FileUtil.getBufferedImage(url);
if (img == null) {
throw new GAPOIException(GapoiResponseCode.URL_IS_NOT_IMG);
}

String format = url.substring(url.lastIndexOf(".") + 1);
ImageIO.write(img, format, response.getOutputStream());

return null;
}

/**
* httpurl图片路径 返回BufferedImage
* @param url
* @return
* @throws Exception
*/
public static BufferedImage getBufferedImage(String url) throws Exception{
URL readUrl = new URL(url);
URLConnection urlConnection = readUrl.openConnection();
urlConnection.setConnectTimeout(1000);
urlConnection.setReadTimeout(5000);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
return ImageIO.read(inputStream);
}
posted @ 2019-11-18 16:06  zfzf1  阅读(403)  评论(0编辑  收藏  举报