From a99c1c5221e1e00979dd42b96a4fd2046b9dec98 Mon Sep 17 00:00:00 2001 From: fwq <582742538@qq.com> Date: 星期三, 01 六月 2022 14:47:02 +0800 Subject: [PATCH] COS执行完关闭连接 --- src/main/java/com/hx/util/COSUtil.java | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 files changed, 43 insertions(+), 1 deletions(-) diff --git a/src/main/java/com/hx/util/COSUtil.java b/src/main/java/com/hx/util/COSUtil.java index 42702d6..62cc1fe 100644 --- a/src/main/java/com/hx/util/COSUtil.java +++ b/src/main/java/com/hx/util/COSUtil.java @@ -48,7 +48,7 @@ //寮�濮嬩笂浼� ObjectMetadata objectMetadata = new ObjectMetadata(); // 璁剧疆杈撳叆娴侀暱搴︿负500 - objectMetadata.setContentLength(500); + objectMetadata.setContentLength(localFile.getSize()); // 璁剧疆 Content type, 榛樿鏄� application/octet-stream,瀵逛簬鏈湴鏂囦欢涓婁紶锛岄粯璁ゆ牴鎹湰鍦版枃浠剁殑鍚庣紑杩涜鏄犲皠 // 锛屼緥濡� jpg 鏂囦欢鏄犲皠 涓篿mage/jpeg瀵逛簬娴佸紡涓婁紶 榛樿鏄� application/octet-stream //objectMetadata.setContentType("application/pdf"); @@ -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