Java從服務器獲得圖片輸入流InputStream,並使用response輸出到頁面


1、創建測試類(FileController.java)

package com.jeff.controller; import java.io.InputStream; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.jeff.utils.HttpUtils; @RestController public class FileController { /** * * @description: 從服務器端獲得圖片,並輸出到頁面 * @author: Jeff * @date: 2019年12月7日 * @param resp */ @RequestMapping("getImage") public void getImage(HttpServletResponse resp) { // 服務器圖片url String urlPath = "http://192.168.1.100:8080/images/jie.jpg"; // 從服務器端獲得圖片,並輸出到頁面 InputStream inputStream = HttpUtils.getInputStream(urlPath); HttpUtils.writeFile(resp, inputStream); } } 

2、創建http工具類(HttpUtils.java)

package com.jeff.utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import javax.servlet.http.HttpServletResponse; public class HttpUtils { /** * * @description: 從服務器獲得一個輸入流(本例是指從服務器獲得一個image輸入流) * @author: Jeff * @date: 2019年12月7日 * @return */ public static InputStream getInputStream(String urlPath) { InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try { URL url = new URL(urlPath); httpURLConnection = (HttpURLConnection) url.openConnection(); // 設置網絡連接超時時間 httpURLConnection.setConnectTimeout(3000); // 設置應用程序要從網絡連接讀取數據 httpURLConnection.setDoInput(true); httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); System.out.println("responseCode is:" + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // 從服務器返回一個輸入流 inputStream = httpURLConnection.getInputStream(); } else { inputStream = httpURLConnection.getErrorStream(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return inputStream; } /** * * @description: 將輸入流輸出到頁面 * @author: Jeff * @date: 2019年12月7日 * @param resp * @param inputStream */ public static void writeFile(HttpServletResponse resp, InputStream inputStream) { OutputStream out = null; try { out = resp.getOutputStream(); int len = 0; byte[] b = new byte[1024]; while ((len = inputStream.read(b)) != -1) { out.write(b, 0, len); } out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (Exception e) { e.printStackTrace(); } } } } 

 https://www.it610.com/article/1282209960490450944.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM