版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lp15203883326/article/details/83008265
其实也就是层次分明的设置放在啊哪个bucketKey
总结起来就是把归属哪个文件的文件名设置好后上传获取最终上传后的链接,返回出去就行了
调用:
//图文上传url
@GetMapping("uploadUrl")
@ResponseBody
public Map<String, String> divUpload(String useFor, String imgUrl) {
try {
if (imgUrl.startsWith("http")) {
String urlWithOutStyle = imgUrl.contains("?") ? imgUrl.substring(0, imgUrl.indexOf("?")) : imgUrl;
String format = urlWithOutStyle.substring(urlWithOutStyle.lastIndexOf(".") + 1);
String bucketKey = OSSUtils.getAliOSSFileName(format, OSSUtils.getAliOSSModuleByUseFor(useFor));
// logger.info("---format----"+format);
return OSSUtils.clientUploadByInputStream(bucketKey,new URL(imgUrl).openStream(),imgUrl.contains("gif")?"com-zhilehuo-images":
"com-zhilehuo-images0",aliConfig);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
public static String getAliOSSFileName(String format, String module) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
return module + sdf.format(now) + now.getTime() + "_" + (int) (Math.random() * 1000) + "." + format;
}
public static String getAliOSSModuleByUseFor(String useFor) {
String module = "wechat/";
if ("material".equals(useFor)) {
module += "material/";
}
return module;
}
public static Map<String, String> clientUploadByInputStream(String bucketKey, InputStream inputStream, String bucketName,AliConfig config) {
OSSClient client = new OSSClient(config.getEndPoint(), config.getAccessKeyId(), config.getAccessKeySecret());
Map<String, String> result = null;
try {
client.putObject(bucketName, bucketKey, inputStream);
result = new HashMap<>();
result.put("result", "ok");
// logger.info("---getCDNAccessURLFromBucketKey----"+OSSUtils.getCDNAccessURLFromBucketKey(bucketKey,bucketName
// ));
result.put("url", OSSUtils.getCDNAccessURLFromBucketKey(bucketKey,bucketName
));
} catch (Exception e) {
// logger.error("uploadImageController: " + ExceptionUtils.getTraceInfo(e));
} finally {
client.shutdown();
}
return result;
}
public static String getCDNAccessURLFromBucketKey(String bucketKey,String bucketName){
String domain = Constant.CDN_ACCESS_URL_DOMAIN;
String style = "@!mp-article";
String resultDomain = bucketName.equals("com-zhilehuo-images")?Constant.CDN_ACCESS_URL_DOMAIN_GIF:domain;
String resultStyle = bucketName.equals("com-zhilehuo-images")?"":style;
return resultDomain + bucketKey + resultStyle;
}