OSS的使用

谁践踏了优雅 2023-10-11 13:59 49阅读 0赞
  • 1.引入maven依赖
  • 2.上传文件
  • 3.断点上传

1.引入maven依赖

  1. <!--引入阿里oss-->
  2. <!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss -->
  3. <dependency>
  4. <groupId>com.aliyun.oss</groupId>
  5. <artifactId>aliyun-sdk-oss</artifactId>
  6. <version>2.2.1</version>
  7. </dependency>

2.上传文件

  1. /**
  2. * 上传文件到oss,返回上传oss之后的地址
  3. * @param file
  4. * @return
  5. */
  6. public static String upLoadFIle2Oss(MultipartFile file,String fileDir){
  7. String ossUrl=null;
  8. try {
  9. OSSClientUtil ossClient = new OSSClientUtil();
  10. String OssImageName = uploadImg2Oss(file,fileDir);
  11. ossUrl = ossClient.getImgUrl(OssImageName,fileDir);
  12. }catch (Exception e){
  13. log.error(e.getMessage());
  14. }
  15. return ossUrl;
  16. }
  17. public String uploadImg2Oss(MultipartFile file,String fileDir){
  18. String originalFilename = file.getOriginalFilename();
  19. String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
  20. Random random = new Random();
  21. String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
  22. InputStream inputStream = null;
  23. try {
  24. inputStream = file.getInputStream();
  25. this.uploadFile2OSS(inputStream, name,fileDir);
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. return name;
  30. }
  31. /**
  32. * 获得图片路径
  33. *
  34. * @param fileUrl
  35. * @return
  36. */
  37. public String getImgUrl(String fileUrl,String fileDir) {
  38. System.out.println(fileUrl);
  39. if (!StringUtils.isEmpty(fileUrl)) {
  40. String[] split = fileUrl.split("/");
  41. return this.getUrl(fileDir + split[split.length - 1]);
  42. }
  43. return null;
  44. }
  45. /**
  46. * 上传到OSS服务器 如果同名文件会覆盖服务器上的
  47. *
  48. * @param instream
  49. * 文件流
  50. * @param fileName
  51. * 文件名称 包括后缀名
  52. * @return 出错返回"" ,唯一MD5数字签名
  53. */
  54. public String uploadFile2OSS(InputStream instream, String fileName,String fileDir) {
  55. String ret = "";
  56. try {
  57. // 创建上传Object的Metadata
  58. ObjectMetadata objectMetadata = new ObjectMetadata();
  59. objectMetadata.setContentLength(instream.available());
  60. objectMetadata.setCacheControl("no-cache");
  61. objectMetadata.setHeader("Pragma", "no-cache");
  62. objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
  63. objectMetadata.setContentDisposition("inline;filename=" + fileName);
  64. // 上传文件
  65. PutObjectResult putResult = ossClient.putObject(bucketName, fileDir + fileName, instream, objectMetadata);
  66. ret = putResult.getETag();
  67. } catch (IOException e) {
  68. logger.error(e.getMessage(), e);
  69. } finally {
  70. try {
  71. if (instream != null) {
  72. instream.close();
  73. }
  74. } catch (IOException e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. return ret;
  79. }

3.断点上传

  1. /**
  2. * 上传视频文件到oss,返回上传oss之后的地址
  3. * @param file
  4. * @return
  5. */
  6. public static String upLoadVideo2Oss(MultipartFile file,String dir){
  7. String ossUrl=null;
  8. try {
  9. OSSClientUtil ossClient = new OSSClientUtil();
  10. File newFile=MultipartFile2File( file);
  11. String OssImageName = ossClient.uploadVideo2OSS(newFile.getPath(),newFile.getName(),dir);
  12. ossUrl = ossClient.getUrl(OssImageName);
  13. if(ossUrl!=null&&!"".equals(ossUrl)){
  14. newFile.delete();
  15. }
  16. }catch (Exception e){
  17. log.error(e.getMessage());
  18. }
  19. return ossUrl;
  20. }
  21. public class OSSClientUtil {
  22. public static final Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
  23. // endpoint
  24. // endpoint以杭州为例,其它region请按实际情况填写
  25. private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  26. // accessKey
  27. private static final String accessKeyId = "LTAIBV6mlkfxp7l";
  28. private static final String accessKeySecret = "TyyLM1HzNdujedZ6dmF9A2xshzScjUS";
  29. // 空间
  30. private String bucketName = "bqkj";
  31. //用户
  32. //头像
  33. private static String USER_PROFILE_IMAGE = "bqkj/campusGang/userInfo/profileImage/";
  34. //内容管理
  35. //附件
  36. public static String CONTENT_MANAGE_ACCESSORY = "bqkj/campusGang/ContentManagement/Accessory/";
  37. //富文本内容
  38. public static String CONTENT_MANAGE_RICH_TEXT = "bqkj/campusGang/ContentManagement/RichTextContent/";
  39. //缩略图
  40. public static String CONTENT_MANAGE_THUMBNAIL = "bqkj/campusGang/ContentManagement/Accessory/";
  41. //留言
  42. //缩略图
  43. public static String LEAVE_MSG_IMAGE = "bqkj/campusGang/leaveMsg/image/";
  44. public static String INVOICE_OCR = "bqkj/campusGang/invoice/ocr/";
  45. private OSSClient ossClient;
  46. public OSSClientUtil() {
  47. ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  48. }
  49. /**
  50. * 初始化
  51. */
  52. public void init() {
  53. ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  54. }
  55. /**
  56. * 销毁
  57. */
  58. public void destory() {
  59. ossClient.shutdown();
  60. }
  61. /**
  62. * 上传图片
  63. *
  64. * @param url
  65. */
  66. public void uploadImg2Oss(String url,String fileDir){
  67. File fileOnServer = new File(url);
  68. FileInputStream fin;
  69. try {
  70. fin = new FileInputStream(fileOnServer);
  71. String[] split = url.split("/");
  72. this.uploadFile2OSS(fin, split[split.length - 1],fileDir);
  73. } catch (FileNotFoundException e) {
  74. e.printStackTrace();
  75. }
  76. }
  77. public String uploadImg2Oss(MultipartFile file,String fileDir){
  78. String originalFilename = file.getOriginalFilename();
  79. String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
  80. Random random = new Random();
  81. String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
  82. InputStream inputStream = null;
  83. try {
  84. inputStream = file.getInputStream();
  85. this.uploadFile2OSS(inputStream, name,fileDir);
  86. } catch (IOException e) {
  87. e.printStackTrace();
  88. }
  89. return name;
  90. }
  91. /**
  92. * 获得图片路径
  93. *
  94. * @param fileUrl
  95. * @return
  96. */
  97. public String getImgUrl(String fileUrl,String fileDir) {
  98. System.out.println(fileUrl);
  99. if (!StringUtils.isEmpty(fileUrl)) {
  100. String[] split = fileUrl.split("/");
  101. return this.getUrl(fileDir + split[split.length - 1]);
  102. }
  103. return null;
  104. }
  105. /**
  106. * 上传到OSS服务器 如果同名文件会覆盖服务器上的
  107. *
  108. * @param instream
  109. * 文件流
  110. * @param fileName
  111. * 文件名称 包括后缀名
  112. * @return 出错返回"" ,唯一MD5数字签名
  113. */
  114. public String uploadFile2OSS(InputStream instream, String fileName,String fileDir) {
  115. String ret = "";
  116. try {
  117. // 创建上传Object的Metadata
  118. ObjectMetadata objectMetadata = new ObjectMetadata();
  119. objectMetadata.setContentLength(instream.available());
  120. objectMetadata.setCacheControl("no-cache");
  121. objectMetadata.setHeader("Pragma", "no-cache");
  122. objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
  123. objectMetadata.setContentDisposition("inline;filename=" + fileName);
  124. // 上传文件
  125. PutObjectResult putResult = ossClient.putObject(bucketName, fileDir + fileName, instream, objectMetadata);
  126. ret = putResult.getETag();
  127. } catch (IOException e) {
  128. logger.error(e.getMessage(), e);
  129. } finally {
  130. try {
  131. if (instream != null) {
  132. instream.close();
  133. }
  134. } catch (IOException e) {
  135. e.printStackTrace();
  136. }
  137. }
  138. return ret;
  139. }
  140. /**
  141. * 断点上传视频
  142. * @param filePath
  143. * @param fileName
  144. * @return
  145. */
  146. public String uploadVideo2OSS(String filePath, String fileName,String dir) {
  147. String ret = "";
  148. try {
  149. fileName=dir+new Date().getTime()+fileName;
  150. UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, fileName);
  151. // The local file to upload---it must exist.
  152. uploadFileRequest.setUploadFile(filePath);
  153. // Sets the concurrent upload task number to 5.
  154. uploadFileRequest.setTaskNum(6);
  155. // Sets the part size to 1MB.
  156. uploadFileRequest.setPartSize(1024 * 1024 * 1);
  157. // Enables the checkpoint file. By default it's off.
  158. uploadFileRequest.setEnableCheckpoint(true);
  159. UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
  160. CompleteMultipartUploadResult multipartUploadResult =
  161. uploadResult.getMultipartUploadResult();
  162. ret=fileName;
  163. System.out.println(multipartUploadResult.getETag());
  164. } catch (OSSException oe) {
  165. System.out.println("Caught an OSSException, which means your request made it to OSS, "
  166. + "but was rejected with an error response for some reason.");
  167. System.out.println("Error Message: " + oe.getErrorMessage());
  168. System.out.println("Error Code: " + oe.getErrorCode());
  169. System.out.println("Request ID: " + oe.getRequestId());
  170. System.out.println("Host ID: " + oe.getHostId());
  171. } catch (ClientException ce) {
  172. System.out.println("Caught an ClientException, which means the client encountered "
  173. + "a serious internal problem while trying to communicate with OSS, "
  174. + "such as not being able to access the network.");
  175. System.out.println("Error Message: " + ce.getMessage());
  176. } catch (Throwable e) {
  177. e.printStackTrace();
  178. } finally {
  179. ossClient.shutdown();
  180. }
  181. return ret;
  182. }
  183. /**
  184. * 删除oss的文件,传参是bqkj/campusGang/userInfo/profileImage/1590730407032.jpg
  185. * @param filePath
  186. * @return
  187. */
  188. public boolean deleteOssFile(String filePath) {
  189. boolean exist = ossClient.doesObjectExist(bucketName, filePath);
  190. if (!exist) {
  191. logger.error("文件不存在,filePath={}", filePath);
  192. return false;
  193. }
  194. logger.info("删除文件,filePath={}", filePath);
  195. ossClient.deleteObject(bucketName, filePath);
  196. ossClient.shutdown();
  197. return true;
  198. }
  199. /**
  200. * Description: 判断OSS服务文件上传时文件的contentType
  201. * @param filenameExtension 文件后缀
  202. * @return String
  203. */
  204. public static String getContentType(String filenameExtension) {
  205. if (filenameExtension.equalsIgnoreCase(".bmp")) {
  206. return "image/bmp";
  207. }
  208. if (filenameExtension.equalsIgnoreCase(".gif")) {
  209. return "image/gif";
  210. }
  211. if (filenameExtension.equalsIgnoreCase(".jpeg") || filenameExtension.equalsIgnoreCase(".jpg")
  212. || filenameExtension.equalsIgnoreCase(".png")) {
  213. return "image/jpeg";
  214. }
  215. if (filenameExtension.equalsIgnoreCase(".html")) {
  216. return "text/html";
  217. }
  218. if (filenameExtension.equalsIgnoreCase(".txt")) {
  219. return "text/plain";
  220. }
  221. if (filenameExtension.equalsIgnoreCase(".vsd")) {
  222. return "application/vnd.visio";
  223. }
  224. if (filenameExtension.equalsIgnoreCase(".pptx") || filenameExtension.equalsIgnoreCase(".ppt")) {
  225. return "application/vnd.ms-powerpoint";
  226. }
  227. if (filenameExtension.equalsIgnoreCase(".docx") || filenameExtension.equalsIgnoreCase(".doc")) {
  228. return "application/msword";
  229. }
  230. if (filenameExtension.equalsIgnoreCase(".xml")) {
  231. return "text/xml";
  232. }
  233. if (filenameExtension.equalsIgnoreCase(".pdf")) {
  234. return "application/pdf";
  235. }
  236. return "image/jpeg";
  237. }
  238. /**
  239. * 获得url链接
  240. *
  241. * @param key
  242. * @return
  243. */
  244. public String getUrl(String key) {
  245. // 设置URL过期时间为10年 3600l* 1000*24*365*10
  246. Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
  247. // 生成URL
  248. URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
  249. if (url != null) {
  250. return url.toString();
  251. }
  252. return null;
  253. }
  254. }

发表评论

表情:
评论列表 (有 0 条评论,49人围观)

还没有评论,来说两句吧...

相关阅读