Java將遠程服務器上的文件經過本地服務器中轉後輸出至前端

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
URL imgUrl = null;
InputStream is = null;
OutputStream outStream = null;
HttpURLConnection httpUrl = null;
try{
    imgUrl = new URL(filename);
    httpUrl = (HttpURLConnection) imgUrl.openConnection();
    httpUrl.connect();
    httpUrl.getInputStream();
    is = httpUrl.getInputStream();

    outStream = response.getOutputStream();
    response.setContentType("image/jpeg");
    //創建一個Buffer字符串
    byte[] buffer = new byte[1024];
    //每次讀取的字符串長度,如果爲-1,代表全部讀取完畢
    int len = 0;
    //使用一個輸入流從buffer裏把數據讀取出來
    while( (len=is.read(buffer)) != -1 ){
        //用輸出流往buffer裏寫入數據,中間參數代表從哪個位置開始讀,len代表讀取的長度
        outStream.write(buffer, 0, len);
    }
}catch (Exception e) {
    e.printStackTrace();
}
finally{
    if(is != null)
    {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if(outStream != null) {
        try {
            outStream.flush();
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if(httpUrl != null) {
        httpUrl.disconnect();
    }
}
發佈了123 篇原創文章 · 獲贊 64 · 訪問量 63萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章