直接获取网络流,根据流上传到oss
/**
* 主要是这个代码
**/
public String downLoadFromUrl(String urlStr, String filePath) throws IOException {
//把地址转换成URL对象
URL url = new URL(urlStr);
//创建http链接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//请求OSS方法 (这里可以替换成自己带oss上传代码)
String resUrl = uploadFileWithRetry(inputStream,filePath);
return resUrl;
}
大致代码是这样
/**
* 将网络图片转换成流并进行oss上传
* 传入网络图片地址和要存储的oss路径
**/
public String downLoadFromUrl(String urlStr, String filePath) throws IOException {
//把地址转换成URL对象
URL url = new URL(urlStr);
//创建http链接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//请求OSS方法
String resUrl = uploadFileWithRetry(inputStream,filePath);
return resUrl;
}
// 你的oss域名
public static final String BASE_URL = "https://xxx.cn/";
// 存储桶相当于电脑本地的文件夹
private static final String DEFAULT_BUCKET_NAME = "xxxx";
public String uploadFileWithRetry(InputStream inputStream, String fileName) {
uploadFile(DEFAULT_BUCKET_NAME, inputStream,fileName);
return BASE_URL + fileName;
}
private static final String END_POINT = "http://xxxx.com";
private static final String ACCESS_KEY = "xxxxx";
private static final String ACCESS_SECRET = "xxxxx";
public void uploadFile(String bucketName, InputStream inputStream, String fileName) {
OSSClient client = new OSSClient(END_POINT, ACCESS_KEY, ACCESS_SECRET);
try {
client.putObject(bucketName, fileName, inputStream);
} catch (Exception var10) {
log.error(var10.getMessage(), var10);
throw var10;
}
}