You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

187 lines
6.9 KiB

  1. package com.simple.controller;
  2. import com.amazonaws.AmazonClientException;
  3. import com.amazonaws.AmazonServiceException;
  4. import com.amazonaws.auth.AWSCredentials;
  5. import com.amazonaws.auth.AWSCredentialsProvider;
  6. import com.amazonaws.auth.BasicAWSCredentials;
  7. import com.amazonaws.services.s3.AmazonS3;
  8. import com.amazonaws.services.s3.AmazonS3ClientBuilder;
  9. import com.amazonaws.services.s3.model.CannedAccessControlList;
  10. import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
  11. import com.amazonaws.services.s3.model.ObjectMetadata;
  12. import com.amazonaws.services.s3.model.PutObjectRequest;
  13. import com.simple.common.ResultData;
  14. import com.simple.config.AwsProperty;
  15. import io.swagger.annotations.Api;
  16. import io.swagger.annotations.ApiOperation;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.beans.factory.annotation.Value;
  21. import org.springframework.web.bind.annotation.PostMapping;
  22. import org.springframework.web.bind.annotation.RequestMapping;
  23. import org.springframework.web.bind.annotation.RequestParam;
  24. import org.springframework.web.bind.annotation.RestController;
  25. import org.springframework.web.multipart.MultipartFile;
  26. import java.io.BufferedInputStream;
  27. import java.io.File;
  28. import java.io.FileOutputStream;
  29. import java.io.IOException;
  30. import java.net.URL;
  31. import java.util.HashMap;
  32. import java.util.Map;
  33. import java.util.UUID;
  34. @RestController
  35. @RequestMapping(value = "upload")
  36. @Api(description = "文件上传接口")
  37. public class UploadController {
  38. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  39. @Value("${fileUpload.path}")
  40. private String filePath;
  41. @Value("${fileUpload.server}")
  42. private String server;
  43. @Autowired
  44. private AwsProperty awsProperty;
  45. /**
  46. * 上传文件
  47. *
  48. * @param multiReq
  49. * @return
  50. * @throws Exception
  51. */
  52. @PostMapping(value = "/fileUpload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
  53. @ApiOperation("上传文件")
  54. public ResultData fileUpload(@RequestParam("file") MultipartFile multiReq) {
  55. ResultData data = new ResultData();
  56. FileOutputStream fos = null;
  57. BufferedInputStream fs = null;
  58. try {
  59. File targetFile = new File(filePath);
  60. if (!targetFile.exists()) {
  61. targetFile.mkdirs();
  62. }
  63. String fileName = UUID.randomUUID().toString();
  64. int dot = multiReq.getOriginalFilename().lastIndexOf('.');
  65. fileName = fileName + multiReq.getOriginalFilename().substring(dot, multiReq.getOriginalFilename().length());
  66. fos = new FileOutputStream(new File(filePath + File.separator + fileName));
  67. fs = (BufferedInputStream) multiReq.getInputStream();
  68. byte[] buffer = new byte[1024];
  69. int len = 0;
  70. while ((len = fs.read(buffer)) != -1) {
  71. fos.write(buffer, 0, len);
  72. }
  73. fos.close();
  74. fs.close();
  75. data.code = ResultData.SUCCESS;
  76. Map<String, String> map = new HashMap<>();
  77. map.put("imgarray", server + "/" + fileName);
  78. data.data = map;
  79. } catch (Exception e) {
  80. e.printStackTrace();
  81. data.code = ResultData.ERROR;
  82. data.message = "上传失败";
  83. } finally {
  84. if (fos != null) {
  85. try {
  86. fos.close();
  87. } catch (IOException e) {
  88. e.printStackTrace();
  89. }
  90. }
  91. if (fs != null) {
  92. try {
  93. fs.close();
  94. } catch (IOException e) {
  95. e.printStackTrace();
  96. }
  97. }
  98. }
  99. return data;
  100. }
  101. /**
  102. * 上传文件
  103. *
  104. * @param multiReq
  105. * @return
  106. * @throws Exception
  107. */
  108. @PostMapping(value = "/awsFileUpload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
  109. @ApiOperation("上传文件")
  110. public ResultData awsfileUpload(@RequestParam("file") MultipartFile multiReq) {
  111. ResultData data = new ResultData();
  112. ObjectMetadata metadata = new ObjectMetadata();
  113. metadata.setContentType(multiReq.getContentType());
  114. metadata.setContentLength(multiReq.getSize());
  115. FileOutputStream fos = null;
  116. BufferedInputStream fs = null;
  117. try {
  118. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  119. .withRegion(awsProperty.getClientRegion())
  120. .withCredentials(new AWSCredentialsProvider() {
  121. @Override
  122. public AWSCredentials getCredentials() {
  123. return new BasicAWSCredentials(awsProperty.getAccess(), awsProperty.getSecret());
  124. }
  125. @Override
  126. public void refresh() {
  127. }
  128. })
  129. .build();
  130. String fileName = UUID.randomUUID().toString();
  131. int dot = multiReq.getOriginalFilename().lastIndexOf('.');
  132. fileName = fileName + multiReq.getOriginalFilename().substring(dot, multiReq.getOriginalFilename().length());
  133. s3.putObject(
  134. new PutObjectRequest(awsProperty.getBucketName(), fileName, multiReq.getInputStream(), metadata)
  135. .withCannedAcl(CannedAccessControlList.PublicRead));
  136. GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(awsProperty.getBucketName(), fileName);
  137. URL url = s3.generatePresignedUrl(urlRequest);
  138. logger.info(url.toString());
  139. data.code = ResultData.SUCCESS;
  140. Map<String, String> map = new HashMap<>();
  141. map.put("imgarray", url.toString());
  142. data.data = map;
  143. return data;
  144. } catch (AmazonServiceException ase) {
  145. data.code = ResultData.ERROR;
  146. logger.warn("Caught an AmazonServiceException, which " +
  147. "means your request made it " +
  148. "to Amazon S3, but was rejected with an error response" +
  149. " for some reason.");
  150. logger.warn(ase.getMessage());
  151. } catch (AmazonClientException ace) {
  152. data.code = ResultData.ERROR;
  153. logger.warn("Caught an AmazonClientException, which " +
  154. "means the client encountered " +
  155. "an internal error while trying to " +
  156. "communicate with S3, " +
  157. "such as not being able to access the network.");
  158. logger.warn("Error Message: " + ace.getMessage());
  159. } catch (IOException ioe) {
  160. data.code = ResultData.ERROR;
  161. logger.warn("Caught an IOException: " + ioe.getMessage());
  162. }
  163. return data;
  164. }
  165. }