JAVA inputstream获取网络图片、视频不全问题
问题记录:
获取网络视频、图片后上传到MinIo图片或视频不全问题
获取网络视频、图片后上传到MinIo图片或视频不全问题
原因:有的网络请求后会分批给你返回流,,需要持续获取
使用下边工具类去获取
代码
.
package com.my.removewatermark.utils.minio;
import org.apache.commons.lang3.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 文件处理工具类
*/
public class FileUtils {
/**
* 通过网络地址获取文件InputStream(持续获取)
*
* @param path 地址
* @return
*/
public static InputStream returnBitMap(String path) {
if (StringUtils.isBlank(path)) {
return null;
}
URL url = null;
InputStream is = null;
byte[] data = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
// 得到网络返回的输入流
is = conn.getInputStream();
// 重要:readStream
data = readStream(is);
} catch (Exception e) {
e.printStackTrace();
}
InputStream inputStream = new ByteArrayInputStream(data);
return inputStream;
}
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
}