Java从服务器获得图⽚输⼊流InputStream,并使⽤response输出
到页⾯
1、创建测试类(FileController.java)
package ller;
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 = "192.168.1.100:8080/images/jie.jpg";
/
/ 从服务器端获得图⽚,并输出到页⾯
InputStream inputStream = InputStream(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.HttpURLConnection;
import java.MalformedURLException;
import java.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 = ResponseCode();
System.out.println("responseCode is:" + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
// 从服务器返回⼀个输⼊流
inputStream = InputStream();
} else {
inputStream = ErrorStream();
}
} 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 = OutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len = ad(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();
}
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。