1. 程式人生 > >服務端讀取圖片內容返回前端,解決圖片跨域問題

服務端讀取圖片內容返回前端,解決圖片跨域問題

最近在配合前端開發,開發一個圖片裁剪功能的時候,遇到一個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呼叫網路圖片,即可完美解決圖片跨域問題。