private static boolean upload(OSSClient client, String bucketName, String key, String filePath) {
int maxTry = 3;
int downloadTurn = 0;
boolean uploadSuccess = false;
while (downloadTurn < maxTry) {
try {
File file = new File(filePath);
ObjectMetadata objectMeta = new ObjectMetadata();
objectMeta.setContentLength(file.length());
if (!client.doesObjectExist(bucketName, key)) {
InputStream input = new FileInputStream(file);
client.putObject(bucketName, key, input, objectMeta);
uploadSuccess = true;
break;
} else {
uploadSuccess = true;
break;
}
} catch (Exception e) {
logger.error(e);
maxTry++;
}
}
return uploadSuccess;
}
/**
* 文件上传
*
* @return
*/
public String upload(File file) {
String filepath = file.getAbsolutePath();
OSSClient client = new OSSClient(bucketSource, accessKeyId, secretAccessKey);
//上传图片
String datePath = sdf.format(new Date()).replaceAll("-", "");
Calendar calendar = Calendar.getInstance();
String key = prefix + "/image/" + datePath + "/" + calendar.get(Calendar.HOUR_OF_DAY) + "/" + file.getName();
boolean isSuccess = upload(client, bucketName, key, filepath);//指定bucket
if (!isSuccess) {
throw new RuntimeException("上传失败!");
}
return host + key;
}
@Override
public String uploadImage(String imageUrl) {
try {
File file = download(imageUrl);
String ossPath = ossUtil.upload(file);
file.delete();
return ossPath;
} catch (Exception e) {
logger.error(e);
throw new RuntimeException("上传失败");
}
}
/**
* 下载文件
*
* @param imageUrl
* @return
* @throws IOException
*/
private File download(String imageUrl) throws IOException {
String suffix = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);
File tempFile = File.createTempFile("img", "." + suffix);
tempFile.deleteOnExit();
URL url = new URL(imageUrl);
URLConnection con = url.openConnection();
con.setConnectTimeout(5 * 1000);
try (InputStream is = con.getInputStream()) {
byte[] bs = new byte[1024];
int len;
try (OutputStream os = new FileOutputStream(tempFile)) {
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
}
}
return tempFile;
}
致力于写一手低调而又专业的代码