当前位置:   article > 正文

java实现基于AmazonS3文件上传、下载、删除操作_amazons3clientbuilder快速下载大文件

amazons3clientbuilder快速下载大文件

  1、创建工具类 AwsS3Utils 

  1. import com.amazonaws.AmazonServiceException;
  2. import com.amazonaws.SdkClientException;
  3. import com.amazonaws.auth.AWSStaticCredentialsProvider;
  4. import com.amazonaws.auth.BasicAWSCredentials;
  5. import com.amazonaws.client.builder.AwsClientBuilder;
  6. import com.amazonaws.services.s3.AmazonS3;
  7. import com.amazonaws.services.s3.AmazonS3ClientBuilder;
  8. import com.amazonaws.services.s3.model.*;
  9. import java.io.File;
  10. /**
  11. * 工具类:S3服务器中文件上传、删除操作(用来存储jmeter脚本中参数化文件)
  12. */
  13. public class AwsS3Utils {
  14. private static org.apache.logging.log4j.Logger logger;
  15. private static final String FILE_TYPE = "fileType";
  16. //隐私信息已模糊处理(keyID、key、endpoint、bucket)
  17. /**
  18. * keyID
  19. */
  20. private static String accessKeyID = "*************";
  21. /**
  22. * key
  23. */
  24. private static String secretKey = "************************";
  25. /**
  26. * endpoint
  27. */
  28. private static String endpoint = "https://xxx.b.xxxxx.cn:443/";
  29. /**
  30. * default bucket
  31. */
  32. private static String defaultBucket = "xxxxxxxx";
  33. /**
  34. * 向 AWS 客户端明确提供凭证
  35. */
  36. private static final BasicAWSCredentials AWS_CREDENTIALS = new BasicAWSCredentials(accessKeyID, secretKey);
  37. /**
  38. * s3 客户端
  39. */
  40. private static final AmazonS3 S3 = AmazonS3ClientBuilder.standard()
  41. .withCredentials(new AWSStaticCredentialsProvider(AWS_CREDENTIALS))
  42. .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, ""))
  43. .build();
  44. /**
  45. * 存放文件至s3
  46. *
  47. * @param bucketName 桶名称 AmazonS3BucketConstant
  48. * @param key key名称
  49. * @param file 文件
  50. * @return PutObjectResult
  51. */
  52. public static PutObjectResult putFile(String bucketName, String key, File file) {
  53. long startMillis = System.currentTimeMillis();
  54. long endMillis;
  55. PutObjectResult result = null;
  56. try {
  57. PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
  58. String name = file.getName();
  59. //新增文件目录 performanceFile
  60. // 记录文件类型
  61. ObjectMetadata metadata = new ObjectMetadata();
  62. metadata.addUserMetadata(FILE_TYPE, name.substring(name.lastIndexOf(".") + 1));
  63. putObjectRequest.setMetadata(metadata);
  64. result = S3.putObject(putObjectRequest);
  65. endMillis = System.currentTimeMillis();
  66. } catch (AmazonServiceException e) {
  67. endMillis = System.currentTimeMillis();
  68. } catch (SdkClientException e) {
  69. // Amazon S3 couldn't be contacted for a response, or the client
  70. // couldn't parse the response from Amazon S3.
  71. }
  72. return result;
  73. }
  74. /**
  75. * 根据文件名称进行删除
  76. * @param bucketName
  77. * @param key
  78. * @return
  79. */
  80. public static void delFile(String bucketName, String key){
  81. if(S3.doesBucketExistV2(bucketName)==false){
  82. logger.info(bucketName+"不存在");
  83. return ;
  84. }
  85. //根据桶名及文件夹名获取该桶该文件夹操作对象
  86. ListObjectsRequest lor = new ListObjectsRequest().withBucketName(defaultBucket).withPrefix("perfFile/");
  87. ObjectListing objectListing = S3.listObjects(lor);
  88. String str_key = null;
  89. //根据操作对象列出所有文件对象,单个对象使用objectSummary.getKey()即可获取此文件完整路径,配合桶名可以用于操作
  90. for(S3ObjectSummary objectSummary : objectListing.getObjectSummaries()){
  91. str_key = objectSummary.getKey();
  92. //文件名是否匹配
  93. if(str_key.matches(key)){
  94. //根据桶名及key信息进行删除
  95. S3.deleteObject(bucketName,key);
  96. break;
  97. }
  98. }
  99. }
  100. public static void delFiles(String key){
  101. delFile(defaultBucket,key);
  102. }
  103. public static PutObjectResult putFile(String key, File file) {
  104. return putFile(defaultBucket, key, file);
  105. }
  106. /**
  107. * 读取文件
  108. * @param bucketName 桶名称 AmazonS3BucketConstant
  109. * @param key key名称
  110. * @return S3Object: s3Object.getBucketName(); s3Object.getKey(); InputStream inputStream = s3Object.getObjectContent()...
  111. * 务必关闭 S3Object: s3Object.close();
  112. */
  113. public static S3Object getFile(String bucketName, String key) {
  114. long startMillis = System.currentTimeMillis();
  115. long endMillis;
  116. S3Object s3Object = null;
  117. try {
  118. s3Object = S3.getObject(bucketName, key);
  119. endMillis = System.currentTimeMillis();
  120. } catch (AmazonServiceException e) {
  121. endMillis = System.currentTimeMillis();
  122. } catch (SdkClientException e) {
  123. // Amazon S3 couldn't be contacted for a response, or the client
  124. // couldn't parse the response from Amazon S3.
  125. }
  126. return s3Object;
  127. }
  128. public static S3Object getFile(String key) {
  129. return getFile(defaultBucket, key);
  130. }
  131. }

2、controller层调用示例

  1. @RequestMapping("/parametric")
  2. @RestController
  3. public class ParametricController {
  4. private ParametricService parametricService ;
  5. public final Logger logger= LoggerFactory.getLogger(this.getClass());
  6. /**
  7. * 文件上传
  8. * @param multipartFile
  9. * @param parametricFilePath
  10. * @param parametricFileS3Path
  11. * @throws Exception
  12. */
  13. @RequestMapping(method = RequestMethod.POST,value ="/create")
  14. public void create(@RequestParam("file") MultipartFile multipartFile,
  15. @RequestParam("parametricFilePath") String parametricFilePath,
  16. @RequestParam("parametricFileS3Path") String parametricFileS3Path) throws Exception{
  17. //空文件限制
  18. if(multipartFile.isEmpty()){
  19. return "上传文件不能为空!";
  20. }
  21. //文件大小限制,最大单文件20M
  22. if(multipartFile.getSize()>20971520){
  23. return "上传文件大小超过20M!";
  24. }
  25. //创建s3 client对象
  26. AwsS3Utils awsS3Utils=new AwsS3Utils();
  27. String localFileName=multipartFile.getOriginalFilename();//获取文件名称
  28. String s3Path="perfFile/";
  29. String key=s3Path+localFileName;//性能测试参数化文件s3服务器存放位置
  30. String fileName = localFileName.substring(0,localFileName.length()-4);
  31. String last4Str=localFileName.substring(localFileName.length()-4);//文件名后缀
  32. String localFilePath="D:\\testDownloading";
  33. //文件类型判断,只能为CSV、txt类型
  34. if(!last4Str.equalsIgnoreCase(".csv")){
  35. if(!last4Str.equalsIgnoreCase(".txt")){
  36. return "只能上传csv、txt两种类型的文件!";
  37. }
  38. }
  39. //根据上传的文件名称去参数化文件数据库中查询是否存在重名
  40. if(parametricService.isExistFile(fileName)){
  41. return "已存在重名文件,请重命名后上传!";
  42. }
  43. //将multipartFile转为File
  44. File uploadFile=new File(localFileName);
  45. FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),uploadFile);
  46. if(uploadFile.exists()){
  47. uploadFile.deleteOnExit();
  48. }
  49. PutObjectResult putObjectResult=awsS3Utils.putFile(key,uploadFile);
  50. logger.info("文件"+localFileName+"上传到S3服务器成功!");
  51. }
  52. /**
  53. *从s3服务器中下载参数化文件到本地指定目录
  54. *@author by junior
  55. * @date 2020/7/27.
  56. * @param key 文件KEY
  57. * @param targetFilePath 本地文件存放路径
  58. * @throws IOException
  59. */
  60. @RequestMapping(method = RequestMethod.GET,value ="/download")
  61. public static void amazonS3Downloading( @RequestParam("key") String key,@RequestParam("targetFilePath") String targetFilePath) throws IOException {
  62. S3Object parameterFile= AwsS3Utils.getFile(key);
  63. if(parameterFile!=null){
  64. InputStream inputStream=null;
  65. FileOutputStream fileOutputStream=null;
  66. byte[] data=null;
  67. try {
  68. //获取S3object对象文本信息
  69. inputStream=parameterFile.getObjectContent();
  70. data =new byte[inputStream.available()];
  71. int len=0;
  72. fileOutputStream=new FileOutputStream(targetFilePath);
  73. while((len=inputStream.read(data)) != -1){
  74. fileOutputStream.write(data,0,len);
  75. }
  76. logger.info("*********下载文件成功!*********");
  77. } catch (IOException e) {
  78. e.printStackTrace();
  79. } finally {
  80. if(fileOutputStream!=null){
  81. try {
  82. fileOutputStream.close();//文件流关闭
  83. } catch (IOException e) {
  84. e.printStackTrace();
  85. }
  86. }
  87. if(inputStream!=null){
  88. try {
  89. inputStream.close();//文件流关闭
  90. } catch (IOException e) {
  91. e.printStackTrace();
  92. }
  93. }
  94. }
  95. }
  96. /**
  97. * 参数化文件信息删除
  98. * @param parametricId
  99. * @return
  100. * @throws Exception
  101. */
  102. @RequestMapping(method = RequestMethod.DELETE,value = "/delete")
  103. public void delete(@RequestParam Integer parametricId) throws Exception{
  104. Integer resultDel = 0;
  105. Result<InterfaceParametricMappingRecord> records = interfaceParametricMappingDao.selectInterfaceParametricMappingByParametricId(parametricId);
  106. //关联表中未存在引用
  107. if (records.size() == 0 && records != null) {
  108. //删除S3服务器上指定文件
  109. Result<ParametricRecord> pRecord = parametricDao.selectParametricById(parametricId);
  110. if (pRecord != null && pRecord.size() > 0) {
  111. AwsS3Utils awsS3Utils = new AwsS3Utils();
  112. String paraName = pRecord.get(0).getParametricFileName()+pRecord.get(0).getParametricFileSuffix();
  113. //性能测试参数化文件s3服务器存放位置
  114. String s3Path = "perfFile/";
  115. String key = s3Path + paraName;
  116. //删除S3服务器上指定文件
  117. awsS3Utils.delFiles(key);
  118. }
  119. resultDel = parametricDao.delParametricById(parametricId);
  120. }
  121. }
  122. }

如觉得对你有帮助,请记得点个赞,个人整理不易....

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

闽ICP备14008679号