腾讯云cos服务器上传图片

腾讯云cos服务器上传图片

2018年11月21日 19:09:11 卧蚕文逗 阅读数:1011

1、首先去腾讯云cos官网注册账号,选择【对象存储】;

腾讯云cos服务器上传图片

2、接下来创建【存储桶】,【存储桶】的意思类似于单独的服务器空间,只有创建了存储桶才能存储资源;

腾讯云cos服务器上传图片

3、系统会根据存储桶的名称 自动生成一个独有的域名;

腾讯云cos服务器上传图片

4、存储空间搞定了,接下来就是从本地上传图片到云服务器了;同时腾讯云也提供了SDK文档和API文档,供我们借鉴,还是相当清楚的;

腾讯云cos服务器上传图片

 

5、上传图片代码,需要注意的是区域,要和服务器上存储桶列表的【所属区域】字段一致;

 
  1. package com.cos.web;

  2.  
  3. import java.io.File;

  4. import java.net.URL;

  5. import java.util.Date;

  6.  
  7. import com.qcloud.cos.COSClient;

  8. import com.qcloud.cos.ClientConfig;

  9. import com.qcloud.cos.auth.BasicCOSCredentials;

  10. import com.qcloud.cos.auth.COSCredentials;

  11. import com.qcloud.cos.exception.CosClientException;

  12. import com.qcloud.cos.exception.CosServiceException;

  13. import com.qcloud.cos.model.PutObjectRequest;

  14. import com.qcloud.cos.model.PutObjectResult;

  15. import com.qcloud.cos.model.StorageClass;

  16. import com.qcloud.cos.region.Region;

  17.  
  18. public class Upload {

  19. public static void main(String[] args) {

  20. // 1 初始化用户身份信息API**(secretId, secretKey)

  21. COSCredentials cred = new BasicCOSCredentials("AKIDXuxxx", "71f4FEyWxxx");

  22. // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224

  23. ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing"));

  24. // 3 生成cos客户端

  25. COSClient cosclient = new COSClient(cred, clientConfig);

  26. // 存储桶bucket名需包含appid

  27. String bucketName = "demo-1258118289";

  28. // 指定要上传到 COS 上对象键

  29. // 对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg` 中,对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)

  30. String key = "2.png";

  31. File localFile = new File("src/main/resources/2.png");

  32. PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);

  33. // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)

  34. putObjectRequest.setStorageClass(StorageClass.Standard_IA);

  35. try {

  36. PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);

  37.  
  38. Date expiration = new Date(new Date().getTime() + 5 * 60 * 10000);

  39. URL url = cosclient.generatePresignedUrl(bucketName, key, expiration);

  40. System.out.println("图片在COS服务器上的url:"+url);

  41. // putobjectResult会返回文件的etag

  42. String etag = putObjectResult.getETag();

  43.  
  44. } catch (CosServiceException e) {

  45. e.printStackTrace();

  46. } catch (CosClientException e) {

  47. e.printStackTrace();

  48. }

  49.  
  50. // 关闭客户端

  51. cosclient.shutdown();

  52. }

  53.  
  54. }

6、下载图片的代码

 
  1. package com.cos.web;

  2.  
  3. import java.io.File;

  4.  
  5. import com.qcloud.cos.COSClient;

  6. import com.qcloud.cos.ClientConfig;

  7. import com.qcloud.cos.auth.BasicCOSCredentials;

  8. import com.qcloud.cos.auth.COSCredentials;

  9. import com.qcloud.cos.exception.CosClientException;

  10. import com.qcloud.cos.exception.CosServiceException;

  11. import com.qcloud.cos.model.GetObjectRequest;

  12. import com.qcloud.cos.model.ObjectMetadata;

  13. import com.qcloud.cos.model.PutObjectRequest;

  14. import com.qcloud.cos.model.PutObjectResult;

  15. import com.qcloud.cos.model.StorageClass;

  16. import com.qcloud.cos.region.Region;

  17.  
  18. public class Download {

  19. public static void main(String[] args) {

  20. // 1 初始化用户身份信息(secretId, secretKey)

  21. COSCredentials cred = new BasicCOSCredentials("AKIDXu20jxxxxx","71f4FEyWxxxx");

  22. // 2 设置bucket的区域, COS地域的简称请参照

  23. // https://cloud.tencent.com/document/product/436/6224

  24. ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing"));

  25. // 3 生成cos客户端

  26. COSClient cosclient = new COSClient(cred, clientConfig);

  27. // bucket名需包含appid

  28. String bucketName = "demo-1258118289";

  29. // 对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg` 中,对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)

  30. String key = "1.png";

  31. File downFile = new File("src/main/resources/2.png");

  32. // 指定要下载的文件所在的 bucket 和对象键

  33. GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);

  34. try {

  35. ObjectMetadata downObjectMeta = cosclient.getObject(getObjectRequest, downFile);

  36. // putobjectResult会返回etag

  37. String etag = downObjectMeta.getETag();

  38. System.out.println(etag);

  39. } catch (CosServiceException e) {

  40. e.printStackTrace();

  41. } catch (CosClientException e) {

  42. e.printStackTrace();

  43. }

  44.  
  45. // 关闭客户端

  46. cosclient.shutdown();

  47. }

  48. }

附(图片上传腾讯云cos工具类):

 
  1. public class COSClientUtil {

  2.  
  3. private static final String SECRETID = "AKIDU4T6iUPu8ixxx";

  4. private static final String SECRETKEY = "gBUbVDj6HJxxx";

  5. private static final String APPID = "1252337xxx";

  6. private static final String BUCKETNAME = "claim" + "-" + APPID; // 桶的名称

  7. private static final String REGIONID = "ap-shanghai";// 区域

  8. private static final String KEY = "ClaimPic/";

  9. private static final String host = "https://" + BUCKETNAME + ".cossh.myqcloud.com";

  10.  
  11. /**

  12. * * 初始化CosClient相关配置, appid、accessKey、secretKey、region * @return

  13. */

  14. public static COSClient getCosClient() {

  15. // 1 init userInfo (secretId, secretKey)

  16. // COSCredentials cred = new BasicCOSCredentials(APPID,ACCESSKEY,

  17. // SECRETKEY);

  18. COSCredentials cred = new BasicCOSCredentials(SECRETID, SECRETKEY); // 不传APPID也可以,APPID和ACCESSKE已经关联过

  19. // 2 set bucket region

  20. ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));

  21. // 3 init cosclient

  22. COSClient cosclient = new COSClient(cred, clientConfig);

  23. // bucket name protocol must be {name}-{appid}

  24. return cosclient;

  25. }

  26.  
  27. /**

  28. * 上传文件

  29. *

  30. * @return

  31. */

  32. public static String uploadFile(String fileURL, String fileName) {

  33. InputStream inputStream = null;

  34. ByteArrayOutputStream output = new ByteArrayOutputStream();

  35. if (fileURL.startsWith("http") || fileURL.startsWith("https")) {

  36. try {

  37. URL url = new URL(fileURL);

  38. inputStream = url.openStream();

  39. } catch (MalformedURLException e) {

  40. e.printStackTrace();

  41. } catch (IOException e) {

  42. e.printStackTrace();

  43. }

  44. } else {

  45. try {

  46. inputStream = new FileInputStream(fileURL);

  47. } catch (FileNotFoundException e) {

  48. e.printStackTrace();

  49. } // 绝对路径和相对路径都OK

  50. }

  51. try {

  52. IOUtils.copy(inputStream, output);

  53. } catch (IOException e2) {

  54. e2.printStackTrace();

  55. }

  56.  
  57. return uploadFile(output.toByteArray(), fileName);

  58.  
  59. }

  60.  
  61. public static String uploadFile(byte[] bytes, String fileName) {

  62. String backUrl = "";

  63.  
  64. // String bucket = BUCKETNAME + "-" + APPID;

  65. // String bucket="claim-1252337168";

  66. System.out.println(BUCKETNAME);

  67. String key = KEY + fileName;

  68.  
  69. ObjectMetadata metadata = new ObjectMetadata();

  70. // metadata.setContentType("image/jpeg");

  71.  
  72. metadata.setContentLength(bytes.length);

  73. PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, key, new ByteArrayInputStream(bytes),

  74. metadata);

  75.  
  76. // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)

  77. putObjectRequest.setStorageClass(StorageClass.Standard_IA);

  78. COSClient cc = getCosClient();

  79. try {

  80. PutObjectResult putObjectResult = cc.putObject(putObjectRequest);

  81. // putobjectResult会返回文件的etag

  82. backUrl = host + "/" + key;

  83. System.out.println(backUrl);

  84. return backUrl;

  85. } catch (CosServiceException e) {

  86. e.printStackTrace();

  87. } catch (CosClientException e) {

  88. e.printStackTrace();

  89. }

  90. // 关闭客户端

  91. cc.shutdown();

  92.  
  93. return backUrl;

  94. }

  95.  
  96. public static String uploadFile(ByteArrayInputStream input, String fileName) {

  97. byte[] bytes = null;

  98. try {

  99. bytes = IOUtils.toByteArray(input);

  100. } catch (IOException e) {

  101. e.printStackTrace();

  102. }

  103.  
  104. return uploadFile(bytes, fileName);

  105. }

  106.  
  107. /**

  108. * * 下载文件 * @param bucketName * @param key * @return

  109. */

  110.  
  111. public static String downLoadFile(String bucketName, String key) {

  112. File downFile = new File("D:/downloadTest/" + KEY + "czy_test.png");

  113.  
  114. COSClient cc = getCosClient();

  115. GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);

  116. ObjectMetadata downObjectMeta = cc.getObject(getObjectRequest, downFile);

  117. cc.shutdown();

  118. String etag = downObjectMeta.getETag();

  119.  
  120. return etag;

  121. }

  122.  
  123. /**

  124. * * 删除文件 * @param bucketName * @param key

  125. */

  126. public void deleteFile(String bucketName, String key) {

  127. COSClient cc = getCosClient();

  128. try {

  129. cc.deleteObject(bucketName, key);

  130. } catch (CosClientException e) {

  131. e.printStackTrace();

  132. } finally {

  133. cc.shutdown();

  134. }

  135. }

  136.  
  137. /**

  138. * * 判断桶是否存在 * @param bucketName * @return * @throws CosClientException

  139. * * @throws CosServiceException

  140. */

  141. public static boolean doesBucketExist(String bucketName) throws CosClientException, CosServiceException {

  142. COSClient cc = getCosClient();

  143. boolean bucketExistFlag = cc.doesBucketExist(bucketName);

  144. return bucketExistFlag;

  145. }

  146.  
  147. /**

  148. * * 查看桶文件 * @param bucketName * @return * @throws CosClientException

  149. * * @throws CosServiceException

  150. */

  151. public ObjectListing listObjects(String bucketName) throws CosClientException, CosServiceException {

  152. COSClient cc = getCosClient();

  153. // 获取 bucket 下成员(设置 delimiter)

  154. ListObjectsRequest listObjectsRequest = new ListObjectsRequest();

  155. listObjectsRequest.setBucketName(bucketName);

  156. // 设置 list 的 prefix, 表示 list 出来的文件 key 都是以这个 prefix 开始

  157. listObjectsRequest.setPrefix("");

  158. // 设置 delimiter 为/, 即获取的是直接成员,不包含目录下的递归子成员

  159. listObjectsRequest.setDelimiter("/");

  160. // 设置 marker, (marker 由上一次 list 获取到, 或者第一次 list marker 为空)

  161. listObjectsRequest.setMarker("");

  162. // 设置最多 list 100 个成员,(如果不设置, 默认为 1000 个,最大允许一次 list 1000 个 key)

  163. listObjectsRequest.setMaxKeys(100);

  164. ObjectListing objectListing = cc.listObjects(listObjectsRequest);

  165. // 获取下次 list 的 marker

  166. String nextMarker = objectListing.getNextMarker();

  167. // 判断是否已经 list 完, 如果 list 结束, 则 isTruncated 为 false, 否则为 true

  168. boolean isTruncated = objectListing.isTruncated();

  169. List<COSObjectSummary> objectSummaries = objectListing.getObjectSummaries();

  170. for (COSObjectSummary cosObjectSummary : objectSummaries) {

  171. // get file path

  172. String key = cosObjectSummary.getKey();

  173. // get file length

  174. long fileSize = cosObjectSummary.getSize();

  175. // get file etag

  176. String eTag = cosObjectSummary.getETag();

  177. // get last modify time

  178. Date lastModified = cosObjectSummary.getLastModified();

  179. // get file save type

  180. String StorageClassStr = cosObjectSummary.getStorageClass();

  181. }

  182. return objectListing;

  183. }

  184.  
  185. public static InputStream getImageStream(String url) {

  186. try {

  187. HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

  188.  
  189. connection.setReadTimeout(5000);

  190. connection.setConnectTimeout(5000);

  191. connection.setRequestMethod("GET");

  192. if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {

  193. InputStream inputStream = connection.getInputStream();

  194. System.out.println("进入图片获取***" + inputStream);

  195. return inputStream;

  196. }

  197. } catch (IOException e) {

  198. System.out.println("获取网络图片出现异常,图片路径为:" + url);

  199. e.printStackTrace();

  200. }

  201. return null;

  202. }

  203.  
  204. private static byte[] readBytes(InputStream is) throws Exception {

  205.  
  206. if ((is == null) || (is.available() < 1)) {

  207. return new byte[0];

  208. }

  209. byte[] buff = new byte[8192];

  210. byte[] result = new byte[is.available()];

  211.  
  212. BufferedInputStream in = new BufferedInputStream(is);

  213. int pos = 0;

  214. int nch;

  215. while ((nch = in.read(buff, 0, buff.length)) != -1) {

  216. // int nch;

  217. pos += nch;

  218. }

  219. System.out.println("byte长度为:" + result.length);

  220. in.close();

  221. return result;

  222. }

  223.  
  224. /**

  225. * 获取网络文件的输入流

  226. *

  227. * @param urlStr

  228. * @return

  229. */

  230. public static InputStream getInputStreamByUrl(String urlStr) {

  231. DataInputStream in = null;

  232. try {

  233. URL url = new URL(urlStr);

  234. HttpURLConnection conn = (HttpURLConnection) url.openConnection();

  235. in = new DataInputStream(conn.getInputStream());

  236. } catch (IOException e) {

  237.  
  238. }

  239. System.out.println("转换完成" + in);

  240. return in;

  241. }

  242.  
  243. public static byte[] toByteArray(InputStream in) throws IOException {

  244.  
  245. ByteArrayOutputStream out = new ByteArrayOutputStream();

  246. byte[] buffer = new byte[1024 * 4];

  247. int n = 0;

  248. while ((n = in.read(buffer)) != -1) {

  249. out.write(buffer, 0, n);

  250. }

  251. return out.toByteArray();

  252. }

  253.  
  254. }

 

ps:

 
  1. 1 初始化用户身份信息(secretId, secretKey),在【**管理】里面;

  2. 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/622