当前位置:   article > 正文

Amazon aws s3上传文件,在给定bucket新建文件夹_amazons3创建文件夹

amazons3创建文件夹

Amazon aws s3上传文件,并设置为公共可读

直接上硬菜:

1.依赖

  1. <dependency>
  2. <groupId>com.amazonaws</groupId>
  3. <artifactId>aws-java-sdk-s3</artifactId>
  4. <version>1.11.625</version>
  5. </dependency>

2.编码

  1. public static String uploadToS3(MultipartFile file) throws IOException {
  2. String perfix = "https://xxxxx.s3-us-west-1.amazonaws.com/";
  3. String bucketName = "txxxxx";
  4. if (file.isEmpty()) {
  5. return "上传文件不能为空";
  6. }
  7. ObjectMetadata metadata = new ObjectMetadata();
  8. metadata.setContentType(file.getContentType());
  9. metadata.setContentLength(file.getSize());
  10. String key = UUID.randomUUID().toString().replaceAll("-", "") + "." + getFileType(file.getOriginalFilename());
  11. String fileTypeByContentType = getFileTypeByContentType(file.getContentType());
  12. if ("image".equals(fileTypeByContentType)) {
  13. bucketName = "xxx-img";
  14. perfix = "https://xxx-img.s3-us-west-1.amazonaws.com/";
  15. } else if ("video".equals(fileTypeByContentType)) {
  16. bucketName = "xxx-video1";
  17. perfix = "https://xxx-video1.s3-us-west-1.amazonaws.com/";
  18. } else {
  19. bucketName = "xxxx-other";
  20. perfix = "https://xxx-other.s3-us-west-1.amazonaws.com/";
  21. }
  22. try {
  23. //验证名称为bucketName的bucket是否存在,不存在则创建
  24. if (!checkBucketExists(s3Client, bucketName)) {
  25. s3Client.createBucket(bucketName);
  26. }
  27. zhi
  28. /*之前被误导,一直上传上此的文件,返回一个链接带有有效期,而且最七天,各种想办法,其实是写法就错误了,
  29. 应该用下面的这种写法withCannedAcl,设置ACL权限就好,希望大家避坑*/
  30. //开始上传文件
  31. s3Client.putObject(new PutObjectRequest(bucketName, key, file.getInputStream(), metadata)
  32. .withCannedAcl(CannedAccessControlList.PublicRead));
  33. String url = perfix + key;
  34. if (url == null) {
  35. throw new BizException(GlobalExceptionEnum.SERVER_ERROR.getCode(), " can't get s3 file url!");
  36. }
  37. return url.toString();
  38. } catch (AmazonServiceException ase) {
  39. ase.printStackTrace();
  40. log.info("====================================AWS S3 UPLOAD ERROR START======================================");
  41. log.info("Caught an AmazonServiceException, which means your request made it "
  42. + "to Amazon S3, but was rejected with an error response for some reason.");
  43. log.info("Caught an AmazonServiceException, which means your request made it "
  44. + "to Amazon S3, but was rejected with an error response for some reason.");
  45. log.info("Error Message: " + ase.getMessage());
  46. log.info("HTTP Status Code: " + ase.getStatusCode());
  47. log.info("AWS Error Code: " + ase.getErrorCode());
  48. log.info("Error Type: " + ase.getErrorType());
  49. log.info("Request ID: " + ase.getRequestId());
  50. log.info(ase.getMessage(), ase);
  51. log.info("====================================AWS S3 UPLOAD ERROR END======================================");
  52. throw new BizException(GlobalExceptionEnum.SERVER_ERROR.getCode(), "error occurs during upload to s3!");
  53. } catch (AmazonClientException ace) {
  54. log.info("====================================AWS S3 UPLOAD ERROR START======================================");
  55. log.info("Caught an AmazonClientException, which means the client encountered "
  56. + "a serious internal problem while trying to communicate with S3, "
  57. + "such as not being able to access the network.");
  58. log.info("Error Message: " + ace.getMessage());
  59. log.info("====================================AWS S3 UPLOAD ERROR END======================================");
  60. throw new BizException(GlobalExceptionEnum.SERVER_ERROR.getCode(), "error occurs during upload to s3!");
  61. } finally {
  62. }
  63. }

就是这么硬


在给定bucket新建文件夹

其实非常检查,简单,只需要在key设置的时候,加上文件夹名,再加个斜杆/即可

核心代码在这里,

记得上传改为用线程池,多线程去异步执行就好,如果需要返回结果,则调用callable方法实现,把结果返回给主线程,

以实现线程间通讯

 


今天想记录一下工作中一个场景:

上传一个zip包(是网站的一个主题活动页面,里面是只能有一个html文件和多个css/js/image等之类的资源文件)

后台服务器解压,并上上传到asw的s3存储。

解决步骤

1.upload文件到服务器本地

2.结果zip文件

3.用多线程 实现批量上传文件到s3,并把上传返回的结果记录到内存map中,用以在第4步中替换

4.本来想着服务端去I/O html文件,readline,然后根据step3中的map,遍历该map再替换,发现其实挺慢

5.于是做了决定,让前端自己去修改html中资源路径,直接告诉她替换规则为http://xxxxx/压缩文件名字/资源名

这样就带来的好处

1.可以直接异步去上传这个一个html文件,立刻返回个前端结果

2.步骤3中不需要存每一个上传的返回路径了,他可以完全异步去做,

3.步骤4中也不要去I/O html文件,readline,再去遍历了

好处大大的啊!就这么愉快的决定了

 

代码如下

  1. public static String generatorPage(File zipFile) {
  2. try {
  3. String zipFileOriginalFilename = zipFile.getName();
  4. String zipfileSuffix = FileUtil.getFileType(zipFileOriginalFilename);
  5. if (!zipfileSuffix.equals("zip")){
  6. throw new BizException(GlobalExceptionEnum.UPLOAD_FILE_ONLY_ZIP);
  7. }
  8. //服务器保存路径-------配置文件读取
  9. String serverFilePath = PropertyUtils.getftpProp("upload_zipfile_path");
  10. /**
  11. * step1.上传文件到应用服务器
  12. */
  13. byte[] zipFileByteArrays = getFileByteArray(zipFile);
  14. FileUtil.uploadFile(zipFileByteArrays, serverFilePath, zipFileOriginalFilename);
  15. String uploadFilePath = serverFilePath + zipFileOriginalFilename;
  16. /**
  17. * step2.将该文件解压
  18. */
  19. ZipUtil.unZipFiles(uploadFilePath, serverFilePath);
  20. String unzipFilePath = uploadFilePath.substring(0, uploadFilePath.lastIndexOf("."));
  21. File file = new File(unzipFilePath);
  22. String pageName = file.getName();
  23. List<File> allUnZipFiles = FileUtil.getAllFiles(unzipFilePath);
  24. File htmlFile = null;
  25. /**
  26. * step3.上传解压后的html文件到s3
  27. */
  28. // Map replaceMap = new HashMap();
  29. int htmlfileNumber = 0;
  30. for (File unzipFile : allUnZipFiles) {
  31. String unzipfileName = unzipFile.getName();
  32. String unzipfileSuffix1 = FileUtil.getFileType(unzipfileName);
  33. if (unzipfileSuffix1.equals("html") || unzipfileSuffix1.equals("htm")) {//如果是html文件
  34. htmlFile = unzipFile;
  35. htmlfileNumber++;
  36. }
  37. }
  38. if (htmlfileNumber == 0 || htmlfileNumber > 1) {
  39. throw new BizException(GlobalExceptionEnum.UPLOAD_FILE_HTML_NUMBER);
  40. }
  41. long start = System.currentTimeMillis();
  42. String s3Path = uploadS3ThreadPoolAsync(pageName, htmlFile).get();
  43. long end1 = System.currentTimeMillis();
  44. System.out.println("上传hmtl页面完毕,耗时:" + (end1 - start));
  45. /**
  46. * step4.上传非html文件到s3
  47. */
  48. for (File unzipFile : allUnZipFiles) {
  49. String unzipfileName = unzipFile.getName();
  50. String unzipfileSuffix = FileUtil.getFileType(unzipfileName);
  51. if (!"zip".equals(unzipfileSuffix) && !"DS_Store".equals(unzipfileSuffix) && !"html".equals(unzipfileSuffix) && !"htm".equals(unzipfileSuffix)) {
  52. uploadS3ThreadPoolAsync(pageName, unzipFile);
  53. }
  54. }
  55. //step4.替换html文件中资源路径[这一步省去,让前端同学处理,把所有资源类的文件路径都替换为:
  56. // https://xxxxx.amazonaws.com/压缩包文件名/14769441969842358.png]
  57. //FileUtil.alterStringToCreateNewFile(htmlFile.getAbsolutePath(), replaceMap);
  58. long end2 = System.currentTimeMillis();
  59. System.out.println(" ----多线程,异步发布任务结束(后台异步去运行)-----:" + (end2 - end1));
  60. System.out.println("主线程运行结束,耗时:" + (end2 - start));
  61. return s3Path;
  62. } catch (Exception e) {
  63. e.printStackTrace();
  64. throw new BizException(GlobalExceptionEnum.UPLOAD_GENERATOR_PAGE_FAIL);
  65. }
  66. }
  67. private static Future<String> uploadS3ThreadPoolAsync(String pageName, File htmlFile) throws InterruptedException, ExecutionException {
  68. Future<String> submit = executorService.submit(() -> {
  69. try {
  70. String htmlS3Path = AmazonS3Util.uploadToS3Async(htmlFile, false, pageName);
  71. return htmlS3Path;
  72. } catch (IOException e) {
  73. e.printStackTrace();
  74. return "";
  75. }
  76. });
  77. return submit;
  78. }
  79. /**
  80. *
  81. * @param file 要上传的文件,文件为普通文件
  82. * @param issinglefile 是否是单个文件上传
  83. * @param pageName 活动页压缩名称
  84. * @return
  85. * @throws IOException
  86. */
  87. public static String uploadToS3Async(File file, boolean issinglefile, String pageName) throws IOException {
  88. if (file.length() == 0) {
  89. throw new BizException(GlobalExceptionEnum.UPLOAD_FILE_IS_EMPTY);
  90. }
  91. long size = file.length();
  92. String path = file.getPath();
  93. String originalFilename = file.getName();
  94. InputStream inputStream = new FileInputStream(file);
  95. String contentType = FileUtil.getFileContentTypeByPath(path);
  96. return getUploadS3Path(contentType, originalFilename, size, inputStream, issinglefile, pageName);
  97. }
  98. /**
  99. *
  100. * @param multipartFile 要上传的文件,文件为Multipart文件
  101. * @param issinglefile 是否是单个文件上传
  102. * @param pageName 活动页压缩名称
  103. * @return
  104. * @throws IOException
  105. */
  106. public static String uploadToS3Async(MultipartFile multipartFile, boolean issinglefile, String pageName) throws IOException {
  107. if (multipartFile.isEmpty()) {
  108. throw new BizException(GlobalExceptionEnum.UPLOAD_FILE_IS_EMPTY);
  109. }
  110. String contentType = multipartFile.getContentType();
  111. String originalFilename = multipartFile.getOriginalFilename();
  112. long size = multipartFile.getSize();
  113. InputStream inputStream = multipartFile.getInputStream();
  114. return getUploadS3Path(contentType, originalFilename, size, inputStream, issinglefile, pageName);
  115. }
  116. /**
  117. * 普通单个文件上传
  118. *
  119. * @param contentType
  120. * @param originalFilename
  121. * @param size
  122. * @param inputStream
  123. * @return
  124. */
  125. private static String getUploadS3Path(String contentType, String originalFilename, long size, InputStream inputStream, boolean issinglefile, String pageName) {
  126. if (!issinglefile) {
  127. bucketName = "tfc-page";
  128. perfix = "https://tfc-page.s3-us-west-1.amazonaws.com/";
  129. } else {
  130. String fileTypeByContentType = getFileTypeByContentType(contentType);
  131. if ("image".equals(fileTypeByContentType)) {
  132. bucketName = "tfc-img";
  133. perfix = "https://tfc-img.s3-us-west-1.amazonaws.com/";
  134. } else if ("video".equals(fileTypeByContentType)) {
  135. bucketName = "tfc-video1";
  136. perfix = "https://tfc-video1.s3-us-west-1.amazonaws.com/";
  137. } else {
  138. bucketName = "tfc-other";
  139. perfix = "https://tfc-other.s3-us-west-1.amazonaws.com/";
  140. }
  141. }
  142. return uploadToS3Asyn(contentType, originalFilename, size, inputStream, pageName);
  143. }
  144. private static String uploadToS3Asyn(String contentType, String originalFilename, long size, InputStream inputStream, String pageName) {
  145. Future<String> submit = executorService.submit(() -> {
  146. String key = "";
  147. try {
  148. ObjectMetadata metadata = new ObjectMetadata();
  149. metadata.setContentType(contentType);
  150. metadata.setContentLength(size);
  151. if (pageName == null || "".equals(pageName)) {
  152. key = DateUtil.getDays()+"/"+UUID.randomUUID().toString().replaceAll("-", "") + "." + getFileType(originalFilename);
  153. } else {
  154. key = pageName + "/" + originalFilename;
  155. }
  156. //验证名称为bucketName的bucket是否存在,不存在则创建
  157. if (!checkBucketExists(s3Client, bucketName)) {
  158. s3Client.createBucket(bucketName);
  159. }
  160. System.out.format("线程%s 正在上传 %s",Thread.currentThread().getName(),key);
  161. System.out.println();
  162. //开始上传文件
  163. s3Client.putObject(new PutObjectRequest(bucketName, key, inputStream, metadata)
  164. .withCannedAcl(CannedAccessControlList.PublicRead));
  165. System.out.format("线程%s 上传完毕",Thread.currentThread().getName());
  166. System.out.println();
  167. String url = perfix + key;
  168. return url;
  169. } catch (AmazonServiceException ase) {
  170. System.out.format("-----__------------上传key=%s时异常",key);
  171. ase.printStackTrace();
  172. log.info("====================================AWS S3 UPLOAD ERROR START======================================");
  173. log.info("Caught an AmazonServiceException, which means your request made it "
  174. + "to Amazon S3, but was rejected with an error response for some reason.");
  175. log.info("Caught an AmazonServiceException, which means your request made it "
  176. + "to Amazon S3, but was rejected with an error response for some reason.");
  177. log.info("Error Message: " + ase.getMessage());
  178. log.info("HTTP Status Code: " + ase.getStatusCode());
  179. log.info("AWS Error Code: " + ase.getErrorCode());
  180. log.info("Error Type: " + ase.getErrorType());
  181. log.info("Request ID: " + ase.getRequestId());
  182. log.info(ase.getMessage(), ase);
  183. log.info("====================================AWS S3 UPLOAD ERROR END======================================");
  184. throw new BizException(GlobalExceptionEnum.SERVER_ERROR.getCode(), "error occurs during upload to s3!");
  185. } catch (AmazonClientException ace) {
  186. log.info("====================================AWS S3 UPLOAD ERROR START======================================");
  187. log.info("Caught an AmazonClientException, which means the client encountered "
  188. + "a serious internal problem while trying to communicate with S3, "
  189. + "such as not being able to access the network.");
  190. log.info("Error Message: " + ace.getMessage());
  191. log.info("====================================AWS S3 UPLOAD ERROR END======================================");
  192. throw new BizException(GlobalExceptionEnum.SERVER_ERROR.getCode(), "error occurs during upload to s3!");
  193. } finally {
  194. }
  195. });
  196. String s3Path = null;
  197. try {
  198. s3Path = submit.get();
  199. } catch (InterruptedException e) {
  200. e.printStackTrace();
  201. } catch (ExecutionException e) {
  202. e.printStackTrace();
  203. }
  204. return s3Path;
  205. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/285771
推荐阅读
相关标签
  

闽ICP备14008679号