OSSUtil.java 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package com.jpsoft.smart.modules.common.utils;
  2. import cn.hutool.core.date.DateTime;
  3. import com.aliyun.oss.HttpMethod;
  4. import com.aliyun.oss.OSS;
  5. import com.aliyun.oss.OSSClientBuilder;
  6. import com.aliyun.oss.model.GeneratePresignedUrlRequest;
  7. import com.aliyun.oss.model.OSSObject;
  8. import com.aliyun.oss.model.PutObjectResult;
  9. import com.jpsoft.smart.config.OSSConfig;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.apache.commons.lang3.StringUtils;
  12. import java.io.*;
  13. import java.net.URL;
  14. import java.net.URLConnection;
  15. import java.net.URLEncoder;
  16. import java.util.*;
  17. import java.util.stream.Collectors;
  18. import java.util.zip.ZipEntry;
  19. import java.util.zip.ZipOutputStream;
  20. @Slf4j
  21. public class OSSUtil {
  22. public static String upload(OSSConfig ossConfig,
  23. String subFolder, String fileName,
  24. InputStream fileInputStream) {
  25. Date now = new Date();
  26. Calendar cal = Calendar.getInstance();
  27. cal.setTime(now);
  28. String savePath = ossConfig.getObjectPre();
  29. if (!subFolder.startsWith("/")) {
  30. savePath += "/";
  31. }
  32. savePath += subFolder;
  33. savePath = savePath + "/" + cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH) + 1) + "/";
  34. OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
  35. int index = fileName.indexOf(".");
  36. // String prefix = fileName.substring(0,index);
  37. String ext = fileName.substring(index);
  38. String newFileName = DateTime.now().toString("ddHHmmssSSS") + ext;
  39. String retFileUrl = savePath + newFileName;
  40. // 上传文件流
  41. PutObjectResult result = ossClient.putObject(ossConfig.getBucketName(), retFileUrl, fileInputStream);
  42. // 关闭OSSClient
  43. ossClient.shutdown();
  44. return ossConfig.getUrlPrefix() + "/" + retFileUrl;
  45. }
  46. public static boolean download(String fileUrl,String filePath){
  47. boolean result;
  48. try {
  49. FileOutputStream output = new FileOutputStream(filePath);
  50. URL url = new URL(encodeFileName(fileUrl));
  51. URLConnection conn = url.openConnection();
  52. InputStream input = conn.getInputStream();
  53. byte[] buffs = new byte[1024 * 10];
  54. BufferedInputStream bis = new BufferedInputStream(input, 1024 * 10);
  55. int read;
  56. while ((read = bis.read(buffs, 0, 1024 * 10)) != -1) {
  57. output.write(buffs, 0, read);
  58. }
  59. input.close();
  60. output.close();
  61. result = true;
  62. } catch (Exception e) {
  63. result = false;
  64. log.error(e.getMessage(),e);
  65. }
  66. return result;
  67. }
  68. public static void batchDownload(List<Map<String,Object>> fileList, OutputStream output){
  69. try{
  70. ZipOutputStream zos = new ZipOutputStream(output);
  71. for (Map<String,Object> map : fileList) {
  72. String fileUrl = (String)map.get("fileUrl");
  73. String filePath = (String)map.get("filePath");
  74. String fileName = (String)map.get("fileName");
  75. try {
  76. if (StringUtils.isEmpty(fileName)) {
  77. fileName = fileUrl;
  78. }
  79. if (fileName.indexOf("?") != -1) {
  80. fileName = fileName.substring(0, fileName.indexOf("?"));
  81. }
  82. fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
  83. String zipFile = fileName;
  84. if(StringUtils.isNotEmpty(filePath)){
  85. zipFile = filePath + fileName;
  86. }
  87. ZipEntry zipEntry = new ZipEntry(zipFile);
  88. zos.putNextEntry(zipEntry);
  89. if(StringUtils.isNotEmpty(fileUrl)) {
  90. URL url = new URL(encodeFileName(fileUrl));
  91. URLConnection conn = url.openConnection();
  92. InputStream inputStream = conn.getInputStream();
  93. byte[] buffs = new byte[1024 * 10];
  94. BufferedInputStream bis = new BufferedInputStream(inputStream, 1024 * 10);
  95. int read;
  96. while ((read = bis.read(buffs, 0, 1024 * 10)) != -1) {
  97. zos.write(buffs, 0, read);
  98. }
  99. bis.close();
  100. }
  101. else if(map.containsKey("fileData")){
  102. byte[] fileData = (byte[])map.get("fileData");
  103. zos.write(fileData,0,fileData.length);
  104. }
  105. }
  106. catch(Exception ex){
  107. log.error(ex.getMessage(),ex);
  108. }
  109. }
  110. zos.close();
  111. }
  112. catch(Exception ex){
  113. log.error(ex.getMessage(),ex);
  114. }
  115. }
  116. private static String encodeFileName(String fileUrl) throws Exception{
  117. String[] segements = fileUrl.split("\\?");
  118. String[] arr = segements[0].split("/");
  119. //文件名可能是中文,用utf-8编码
  120. arr[arr.length - 1] = URLEncoder.encode(arr[arr.length - 1],"UTF-8");
  121. String encFileUrl = Arrays.stream(arr).collect(Collectors.joining("/"));
  122. if (segements.length>1){
  123. encFileUrl += "?" + segements[1];
  124. }
  125. return encFileUrl;
  126. }
  127. public static void presignedDownload(OSSConfig ossConfig, List<Map> fileList, OutputStream output){
  128. BufferedInputStream bis = null;
  129. try{
  130. ZipOutputStream zos = new ZipOutputStream(output);
  131. OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
  132. for (Map<String,String> map : fileList) {
  133. try {
  134. String fileUrl = map.get("fileUrl");
  135. String filePath = map.get("filePath");
  136. Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
  137. if (fileUrl.startsWith(ossConfig.getUrlPrefix())) {
  138. fileUrl = fileUrl.substring(ossConfig.getUrlPrefix().length());
  139. }
  140. if (fileUrl.indexOf("?") != -1) {
  141. fileUrl = fileUrl.substring(0, fileUrl.indexOf("?"));
  142. }
  143. if (fileUrl.startsWith("/")) {
  144. fileUrl = fileUrl.substring(1);
  145. }
  146. GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(ossConfig.getBucketName(), fileUrl, HttpMethod.GET);
  147. // 设置过期时间。
  148. request.setExpiration(expiration);
  149. //设置缩放
  150. request.setProcess("image/resize,l_1024,limit_1");
  151. // 生成签名URL(HTTP GET请求)。
  152. URL signedUrl = ossClient.generatePresignedUrl(request);
  153. // 使用签名URL发送请求。
  154. OSSObject ossObject = ossClient.getObject(signedUrl, new HashMap<>());
  155. if (ossObject != null) {
  156. InputStream inputStream = ossObject.getObjectContent();
  157. byte[] buffs = new byte[1024 * 10];
  158. String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
  159. String zipFile = fileName;
  160. if (StringUtils.isNotEmpty(filePath)){
  161. zipFile = filePath + fileName;
  162. }
  163. ZipEntry zipEntry = new ZipEntry(zipFile);
  164. zos.putNextEntry(zipEntry);
  165. bis = new BufferedInputStream(inputStream, 1024 * 10);
  166. int read;
  167. while ((read = bis.read(buffs, 0, 1024 * 10)) != -1) {
  168. zos.write(buffs, 0, read);
  169. }
  170. ossObject.close();
  171. }
  172. }
  173. catch(Exception ex){
  174. log.error(ex.getMessage(),ex);
  175. }
  176. }
  177. zos.close();
  178. ossClient.shutdown();
  179. }
  180. catch(Exception ex){
  181. log.error(ex.getMessage(),ex);
  182. }
  183. finally {
  184. if(bis!=null){
  185. try {
  186. bis.close();
  187. } catch (IOException e) {
  188. e.printStackTrace();
  189. }
  190. }
  191. }
  192. }
  193. }