服务端读取图片内容返回前端,解决图片跨域问题
最近在配合前端开发,开发一个图片裁剪功能的时候,遇到一个oss图片跨域请求,无法访问的问题,索性自己写个接口,先读取图片文件流再直接返回前端。具体代码如下。
1.新建文件流内容封装类FileContent
1 public class FileContent { 2 private byte[] content; 3 private String content_type; 4 5 public byte[] getContent() { 6 return content; 7 } 8 9 public void setContent(byte[] content) { 10 this.content = content; 11 } 12 13 public String getContent_type() { 14 return content_type; 15 } 16 17 public void setContent_type(String content_type) { 18 this.content_type = content_type; 19 } 20 }
2.根据图片链接获取文件流
public static FileContent getImageByte(String img){ //String imgUrl="http://mmbiz.qpic.cn/mmbiz/yqVAqoZvDibEaicDyIvX7dLE9icYnwb2tlOtSzGMCglvqk61JjpW338xMSlJsKPVBiaD6FY1M5MtopJYvWrVYeYwFA/0?wx_fmt=jpeg"; ByteArrayOutputStream outStream = null; FileContent file=new FileContent(); String contentType=""; try { URL url=new URL(img); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10 * 1000); contentType=conn.getHeaderField("Content-Type"); //通过输入流获取图片数据 InputStream inStream = conn.getInputStream(); outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len=inStream.read(buffer)) != -1 ){ outStream.write(buffer, 0, len); } inStream.close(); } catch (IOException e) { e.printStackTrace(); } byte[] content= outStream.toByteArray(); file.setContent(content); file.setContent_type(contentType); return file; }
3.接口获取参数图片链接
@RequestMapping("/read/image") public ResponseEntity<byte[]> getImageContent(HttpServletRequest request){ HttpHeaders responseHeaders = new HttpHeaders(); String imageUrl=request.getParameter("imageUrl"); FileContent file=Utilities.getImageByte(imageUrl); responseHeaders.set("Access-Control-Allow-Origin","*"); responseHeaders.set("Content-Type",file.getContent_type()); return new ResponseEntity<>(file.getContent(), responseHeaders, HttpStatus.OK); }
4.前端可直接通过 域名+/read/image?imageUrl=XXXX调用网络图片,即可完美解决图片跨域问题。