From 2ed1199d48f7207f4a012c04f61e13ac1a8d5154 Mon Sep 17 00:00:00 2001 From: chenjiahe <763432473@qq.com> Date: 星期四, 16 六月 2022 10:27:44 +0800 Subject: [PATCH] 新增请求安全工具 --- src/main/java/com/hx/util/COSUtil.java | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 42 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/hx/util/COSUtil.java b/src/main/java/com/hx/util/COSUtil.java index 0137cac..62cc1fe 100644 --- a/src/main/java/com/hx/util/COSUtil.java +++ b/src/main/java/com/hx/util/COSUtil.java @@ -63,6 +63,48 @@ }else{ imgUrl.append("/"+key); } + cosClient.shutdown(); + return imgUrl.toString(); + + } + + + /** 鍚庣璋冪敤涓婁紶鍥剧墖 + * @param key 涓婁紶璺緞锛堝寘鎷浘鐗囧悕绉板拰鍜屽悗缂�锛夛紝鎸囧畾瑕佷笂浼犲埌 COS 涓婂璞¢敭 + * @param localFile + * @param secretId 鐢ㄦ埛id + * @param secretKey 鐢ㄦ埛绉橀挜 + * @param regionName 瀛樺湪鍩燂紝鍙傝�冭吘璁簯 + * @param bucketName 鎸囧畾瑕佷笂浼犲埌鐨勫瓨鍌ㄦ《 + * @return + * @throws IOException + */ + public static String uploadImg(String key,File localFile,String secretId, String secretKey,String regionName,String bucketName) throws IOException { + + // 1 鍒濆鍖栫敤鎴疯韩浠戒俊鎭紙secretId, secretKey锛夈�� + COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); + // 2 璁剧疆 bucket 鐨勫尯鍩�, COS 鍦板煙鐨勭畝绉拌鍙傜収 https://cloud.tencent.com/document/product/436/6224 + // clientConfig 涓寘鍚簡璁剧疆 region, https(榛樿 http), 瓒呮椂, 浠g悊绛� set 鏂规硶, 浣跨敤鍙弬瑙佹簮鐮佹垨鑰呭父瑙侀棶棰� Java SDK 閮ㄥ垎銆� + Region region = new Region(regionName); + ClientConfig clientConfig = new ClientConfig(region); + // 3 鐢熸垚 cos 瀹㈡埛绔�� + COSClient cosClient = new COSClient(cred, clientConfig); + + // 璁剧疆 Content type, 榛樿鏄� application/octet-stream,瀵逛簬鏈湴鏂囦欢涓婁紶锛岄粯璁ゆ牴鎹湰鍦版枃浠剁殑鍚庣紑杩涜鏄犲皠 + // 锛屼緥濡� jpg 鏂囦欢鏄犲皠 涓篿mage/jpeg瀵逛簬娴佸紡涓婁紶 榛樿鏄� application/octet-stream + //objectMetadata.setContentType("application/pdf"); + PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile); + PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); + + //鎷兼帴璺緞 + StringBuilder imgUrl = new StringBuilder(); + imgUrl.append("https://"+bucketName+".cos."+regionName+".myqcloud.com"); + if(key.startsWith("/")){ + imgUrl.append(key); + }else{ + imgUrl.append("/"+key); + } + cosClient.shutdown(); return imgUrl.toString(); } -- Gitblit v1.8.0