OSSFileService.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. package com.izouma.awesomeadmin.service;
  2. import com.aliyun.oss.OSSClient;
  3. import com.aliyun.oss.model.OSSObject;
  4. import com.aliyun.oss.model.ObjectMetadata;
  5. import com.aliyun.oss.model.PutObjectResult;
  6. import com.izouma.awesomeadmin.util.ImagesUtil;
  7. import com.izouma.awesomeadmin.util.PropertiesFileLoader;
  8. import org.apache.commons.lang.StringUtils;
  9. import org.apache.log4j.Logger;
  10. import org.springframework.stereotype.Service;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import java.io.*;
  14. import java.net.URLEncoder;
  15. import java.text.SimpleDateFormat;
  16. import java.util.Date;
  17. import java.util.List;
  18. import java.util.Random;
  19. import java.util.zip.Adler32;
  20. import java.util.zip.CheckedOutputStream;
  21. import java.util.zip.ZipEntry;
  22. import java.util.zip.ZipOutputStream;
  23. @Service
  24. public class OSSFileService {
  25. /**
  26. * 日志对象
  27. */
  28. private static Logger logger = Logger.getLogger(OSSFileService.class);
  29. private static final String projectName = PropertiesFileLoader.getProperties("projectname");
  30. public String upload(InputStream fin, String path) {
  31. if (path.startsWith("/")) {
  32. path = path.replaceFirst("\\\\/", "");
  33. }
  34. path = projectName + "/" + path;
  35. String aliid = PropertiesFileLoader.getDefaultProperties("aliossid", "");
  36. String alikey = PropertiesFileLoader.getDefaultProperties("aliosskey", "");
  37. String aliossendpoit = "Y".equals(PropertiesFileLoader.getDefaultProperties("alioss_internal_flag", "")) ?
  38. PropertiesFileLoader.getDefaultProperties("aliossendpoitinternal", "") :
  39. PropertiesFileLoader.getDefaultProperties("aliossendpoit", "");
  40. String bucketname = PropertiesFileLoader.getDefaultProperties("alibucketname", "");
  41. logger.info(String.format("OSS上传:\naliid: %s\nalikey: %s\naliossendpoit: %s\nbucketname: %s\npath: %s", aliid, alikey, aliossendpoit, bucketname, path));
  42. OSSClient client = new OSSClient(aliossendpoit, aliid, alikey);
  43. OSSObject object = null;
  44. boolean found = false;
  45. try {
  46. PutObjectResult result = client.putObject(bucketname, path, fin, new ObjectMetadata());
  47. //object = client.getObject(bucketname, path);
  48. // 判断文件是否存在。doesObjectExist还有一个参数isOnlyInOSS,如果为true则忽略302重定向或镜像;如果为false,则考虑302重定向或镜像。
  49. found = client.doesObjectExist(bucketname, path);
  50. System.out.println(found + "path");
  51. } catch (Exception r) {
  52. logger.error("OSS上传异常:", r);
  53. } finally {
  54. try {
  55. fin.close();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. }
  60. client.shutdown();
  61. // 如果不设置content-length, 默认为chunked编码。
  62. if (found) {
  63. return getFullPath(path);
  64. }
  65. return null;
  66. }
  67. private static String getFullPath(String Path) {
  68. if (Path == null || "".equals(Path)) {
  69. return Path;
  70. }
  71. String aliossendpoit = PropertiesFileLoader.getDefaultProperties("aliImageSever", "");
  72. return aliossendpoit + "/" + Path;
  73. }
  74. public String uploadImg(String base64) throws UnsupportedEncodingException {
  75. try {
  76. logger.info("uploadIcon:上传图片");
  77. if (base64 == null) {
  78. return null;
  79. }
  80. Random random = new Random();
  81. StringBuilder randomCode = new StringBuilder();
  82. for (int i = 0; i < 8; i++) {
  83. randomCode.append(Integer.toString(random.nextInt(36), 36));
  84. }
  85. try {
  86. String path = String.format("images/%s-%s.jpg", new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()), randomCode);
  87. return upload(ImagesUtil.GenerateImage(base64), path);
  88. } catch (Exception e) {
  89. e.printStackTrace();
  90. }
  91. } catch (Exception e) {
  92. e.printStackTrace();
  93. logger.error("上传图片异常");
  94. }
  95. return null;
  96. }
  97. /**
  98. * @param objectName 不包含 bucketname 的 path
  99. */
  100. public void deleteObject(String objectName) {
  101. if (StringUtils.isNotEmpty(objectName)) {
  102. String aliid = PropertiesFileLoader.getDefaultProperties("aliossid", "");
  103. String alikey = PropertiesFileLoader.getDefaultProperties("aliosskey", "");
  104. String aliossendpoit = PropertiesFileLoader.getDefaultProperties("aliossendpoit", "");
  105. String bucketname = PropertiesFileLoader.getDefaultProperties("alibucketname", "");
  106. logger.info(String.format("OSS 删除:\naliid: %s\nalikey: %s\naliossendpoit: %s\nbucketname: %s\npath: %s", aliid, alikey, aliossendpoit, bucketname, objectName));
  107. OSSClient client = new OSSClient(aliossendpoit, aliid, alikey);
  108. // 删除文件。
  109. client.deleteObject(bucketname, objectName);
  110. // 关闭OSSClient。
  111. client.shutdown();
  112. }
  113. }
  114. /**
  115. * 批量下载图片
  116. *
  117. * @param keyList ossfileName 逗号分隔。
  118. * @param zipName 压缩包名称
  119. * @param request
  120. * @param response
  121. * @return
  122. */
  123. public HttpServletResponse zipFilesDown(List<String> keyList, String zipName, HttpServletRequest request, HttpServletResponse response) {
  124. String accessKeyId = PropertiesFileLoader.getDefaultProperties("aliossid", "");
  125. String accessKeySecret = PropertiesFileLoader.getDefaultProperties("aliosskey", "");
  126. String endpoint = "Y".equals(PropertiesFileLoader.getDefaultProperties("alioss_internal_flag", "")) ?
  127. PropertiesFileLoader.getDefaultProperties("aliossendpoitinternal", "") :
  128. PropertiesFileLoader.getDefaultProperties("aliossendpoit", "");
  129. String bucketName = PropertiesFileLoader.getDefaultProperties("alibucketname", "");
  130. // endpoint以杭州为例,其它region请按实际情况填写
  131. // 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建
  132. try {
  133. // 初始化
  134. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  135. String fileName = zipName + ".zip";
  136. // 创建临时文件
  137. File zipFile = File.createTempFile(zipName, ".zip");
  138. FileOutputStream f = new FileOutputStream(zipFile);
  139. /**
  140. * 作用是为任何OutputStream产生校验和
  141. * 第一个参数是制定产生校验和的输出流,第二个参数是指定Checksum的类型 (Adler32(较快)和CRC32两种)
  142. */
  143. CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
  144. // 用于将数据压缩成Zip文件格式
  145. ZipOutputStream zos = new ZipOutputStream(csum);
  146. for (String ossfile : keyList) {
  147. try {
  148. // 获取Object,返回结果为OSSObject对象
  149. OSSObject ossObject = ossClient.getObject(bucketName, ossfile);
  150. // 读去Object内容 返回
  151. InputStream inputStream = ossObject.getObjectContent();
  152. // 对于每一个要被存放到压缩包的文件,都必须调用ZipOutputStream对象的putNextEntry()方法,确保压缩包里面文件不同名
  153. zos.putNextEntry(new ZipEntry(ossfile.split("/")[ossfile.split("/").length - 1]));
  154. int bytesRead = 0;
  155. // 向压缩文件中输出数据
  156. while ((bytesRead = inputStream.read()) != -1) {
  157. zos.write(bytesRead);
  158. }
  159. inputStream.close();
  160. zos.closeEntry(); // 当前文件写完,定位为写入下一条项目
  161. } catch (Exception e) {
  162. logger.error("ossfile, 压缩失败", e);
  163. }
  164. }
  165. zos.close();
  166. String header = request.getHeader("User-Agent").toUpperCase();
  167. if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
  168. fileName = URLEncoder.encode(fileName, "utf-8");
  169. fileName = fileName.replace("+", "%20"); //IE下载文件名空格变+号问题
  170. } else {
  171. fileName = new String(fileName.getBytes(), "ISO8859-1");
  172. }
  173. response.reset();
  174. response.setContentType("text/plain");
  175. response.setContentType("application/octet-stream; charset=utf-8");
  176. response.setHeader("Location", fileName);
  177. response.setHeader("Cache-Control", "max-age=0");
  178. response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
  179. FileInputStream fis = new FileInputStream(zipFile);
  180. BufferedInputStream buff = new BufferedInputStream(fis);
  181. BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
  182. byte[] car = new byte[1024];
  183. int l = 0;
  184. while (l < zipFile.length()) {
  185. int j = buff.read(car, 0, 1024);
  186. l += j;
  187. out.write(car, 0, j);
  188. }
  189. // 关闭流
  190. fis.close();
  191. buff.close();
  192. out.close();
  193. ossClient.shutdown();
  194. // 删除临时文件
  195. zipFile.delete();
  196. } catch (Exception e) {
  197. logger.error("压缩失败", e);
  198. }
  199. return response;
  200. }
  201. /**
  202. * 单张图片下载
  203. *
  204. * @param key
  205. * @param request
  206. * @param response
  207. * @return
  208. */
  209. public HttpServletResponse singleFileDown(String key, HttpServletRequest request, HttpServletResponse response) {
  210. String accessKeyId = PropertiesFileLoader.getDefaultProperties("aliossid", "");
  211. String accessKeySecret = PropertiesFileLoader.getDefaultProperties("aliosskey", "");
  212. String endpoint = "Y".equals(PropertiesFileLoader.getDefaultProperties("alioss_internal_flag", "")) ?
  213. PropertiesFileLoader.getDefaultProperties("aliossendpoitinternal", "") :
  214. PropertiesFileLoader.getDefaultProperties("aliossendpoit", "");
  215. String bucketName = PropertiesFileLoader.getDefaultProperties("alibucketname", "");
  216. // endpoint以杭州为例,其它region请按实际情况填写
  217. // 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建
  218. try {
  219. // 初始化
  220. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  221. // 获取Object,返回结果为OSSObject对象
  222. OSSObject ossObject = ossClient.getObject(bucketName, key);
  223. // 读去Object内容 返回
  224. InputStream inputStream = ossObject.getObjectContent();
  225. // 对于每一个要被存放到压缩包的文件,都必须调用ZipOutputStream对象的putNextEntry()方法,确保压缩包里面文件不同名
  226. String fileName = key.split("/")[key.split("/").length - 1];
  227. String header = request.getHeader("User-Agent").toUpperCase();
  228. if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
  229. fileName = URLEncoder.encode(fileName, "utf-8");
  230. fileName = fileName.replace("+", "%20"); //IE下载文件名空格变+号问题
  231. } else {
  232. fileName = new String(fileName.getBytes(), "ISO8859-1");
  233. }
  234. response.reset();
  235. response.setContentType("text/plain");
  236. response.setContentType("application/octet-stream; charset=utf-8");
  237. response.setHeader("Location", fileName);
  238. response.setHeader("Cache-Control", "max-age=0");
  239. response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
  240. BufferedInputStream buff = new BufferedInputStream(inputStream);
  241. BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
  242. byte[] car = new byte[1024];
  243. int l = 0;
  244. while ((l = inputStream.read(car)) != -1) {
  245. if (car.length != 0) {
  246. out.write(car, 0, l);
  247. }
  248. }
  249. // 关闭流
  250. inputStream.close();
  251. buff.close();
  252. out.close();
  253. ossClient.shutdown();
  254. } catch (Exception e) {
  255. logger.error("下载图片失败", e);
  256. }
  257. return response;
  258. }
  259. public boolean doesObjectExist(String path) {
  260. String aliid = PropertiesFileLoader.getDefaultProperties("aliossid", "");
  261. String alikey = PropertiesFileLoader.getDefaultProperties("aliosskey", "");
  262. String aliossendpoit = "Y".equals(PropertiesFileLoader.getDefaultProperties("alioss_internal_flag", "")) ?
  263. PropertiesFileLoader.getDefaultProperties("aliossendpoitinternal", "") :
  264. PropertiesFileLoader.getDefaultProperties("aliossendpoit", "");
  265. String bucketname = PropertiesFileLoader.getDefaultProperties("alibucketname", "");
  266. logger.info(String.format("OSS上传:\naliid: %s\nalikey: %s\naliossendpoit: %s\nbucketname: %s\npath: %s", aliid, alikey, aliossendpoit, bucketname, path));
  267. OSSClient client = new OSSClient(aliossendpoit, aliid, alikey);
  268. boolean found = false;
  269. // 判断文件是否存在。doesObjectExist还有一个参数isOnlyInOSS,如果为true则忽略302重定向或镜像;如果为false,则考虑302重定向或镜像。
  270. found = client.doesObjectExist(bucketname, path);
  271. System.out.println(found + "path");
  272. client.shutdown();
  273. return found;
  274. }
  275. }