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

最近在配合前端開發,開發一個圖片裁剪功能的時候,遇到一個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.接口獲取參數圖片連接app

 @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調用網絡圖片,便可完美解決圖片跨域問題。this

相關文章
相關標籤/搜索