springboot+thymeleaf整合阿里云OOS對象存儲圖片的實現(xiàn)
今天再進(jìn)行創(chuàng)建項目時想使用阿里云oos進(jìn)行存儲圖片 下面進(jìn)行實操
1.先引入pom依賴
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.9.1</version> </dependency>
2.編寫前端thymleeaf代碼tetsfile.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> </style> <body> <img th:src="${url}" alt="" width="300px"> <form action="fileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="fileName"> <input type="submit"> </form> </body> </html>
3.service層編寫
下面的代碼需要4個參數(shù)
package com.xuda.ntf.service; import com.aliyun.oss.*; import com.aliyun.oss.model.*; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.io.File; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.UUID; /** * @author :程序員徐大大 * @description:TODO * @date :2022-05-07 10:33 */ @Service @Slf4j public class AliyunOSSUtilService { /** * 這五個分別是什么下面會說 * aliyun.oss.endpoint=oss-cn-shanghai.aliyuncs.com * aliyun.oss.accessKeyId=L相關(guān)密鑰 * aliyun.oss.secret=eF0相關(guān)密鑰 * aliyun.oss.bucket=yygh-xuda */ public static final String endpoint = "oss-cn-shanghai.aliyuncs.com"; public static final String accessKeyId = "LTA個人密鑰"; public static final String accessKeySecret = "eF0UmiWp2回傳密鑰"; public static final String bucketName = "yygh-xuda回傳name"; public static final String fileHost = "2022/cff"; //圖片頭部 private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); /** * 上傳 * * @param file * @return */ public String upload(File file) { log.info("=========>OSS文件上傳開始:" + file.getName()); // String fileHost=constantProperties.getFilehost(); System.out.println(endpoint + "endpoint"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = format.format(new Date()); if (null == file) { return null; } OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); try { //容器不存在,就創(chuàng)建 if (!ossClient.doesBucketExist(bucketName)) { ossClient.createBucket(bucketName); CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName); createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead); ossClient.createBucket(createBucketRequest); } //創(chuàng)建文件路徑 String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName()); //上傳文件 PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file)); //設(shè)置權(quán)限 這里是公開讀 ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead); if (null != result) { log.info("==========>OSS文件上傳成功,OSS地址:" + fileUrl); return fileUrl; } } catch (OSSException oe) { log.error(oe.getMessage()); } catch (ClientException ce) { log.error(ce.getMessage()); } finally { //關(guān)閉 ossClient.shutdown(); } return null; } /** * @desc 查看文件列表 */ public List<OSSObjectSummary> getObjectList() { OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); // 設(shè)置最大個數(shù)。 final int maxKeys = 200; // 列舉文件。 ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName); listObjectsRequest.setPrefix(fileHost + "/"); ObjectListing objectListing = ossClient.listObjects(listObjectsRequest.withMaxKeys(maxKeys)); List<OSSObjectSummary> sums = objectListing.getObjectSummaries(); return sums; } /** * 獲取文件臨時url * * @param objectName oss中的文件名 * @param */ public String getUrl(String objectName ,long effectiveTime) { OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 設(shè)置URL過期時間 Date expiration = new Date(new Date().getTime() + effectiveTime); GeneratePresignedUrlRequest generatePresignedUrlRequest ; generatePresignedUrlRequest =new GeneratePresignedUrlRequest(bucketName, objectName); generatePresignedUrlRequest.setExpiration(expiration); URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest); return url.toString(); } /** * 刪除OSS中的單個文件 * * @param objectName 唯一objectName(在oss中的文件名字) */ public void delete(String objectName) { try { // 創(chuàng)建OSSClient實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 刪除文件。 ossClient.deleteObject(bucketName, objectName); // 關(guān)閉OSSClient。 ossClient.shutdown(); } catch (Exception e) { e.printStackTrace(); } } }
4.controller層編寫
寫到代碼中取
package com.xuda.ntf.controller; import com.aliyun.oss.model.OSSObjectSummary; import com.xuda.ntf.service.AliyunOSSUtilService; import com.xuda.ntf.service.FileService; import com.xuda.ntf.utils.JsonResult; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author :程序員徐大大 * @description:TODO * @date :2022-05-07 9:39 */ @Slf4j @Controller public class FileApiController { String uploadUrl = ""; @Autowired private AliyunOSSUtilService aliyunOSSUtil; /** * 查看圖片 * */ @RequestMapping("/getAllPic") public String getAllPic(Model model){ // Hashtable hashtable = new Hashtable(); // 顯示圖片 ArrayList<String> listStr = new ArrayList<>(); List<OSSObjectSummary> list = aliyunOSSUtil.getObjectList(); String url = aliyunOSSUtil.getUrl(uploadUrl,5000); /* list.forEach(item -> { // 這個將自己上傳圖片得地址復(fù)制到這里來 listStr.add("https://yygh-xuda.oss-cn-shanghai.aliyuncs.com/"+item.getKey()); } );*/ model.addAttribute("fileNames",listStr); model.addAttribute("url",url); return "testfile.html"; } /** * * @param file 要上傳的文件 * @return */ @RequestMapping("/fileUpload") public String upload(@RequestParam("fileName") MultipartFile file,Model model){ try { if(null != file){ String filename = file.getOriginalFilename(); if(!"".equals(filename.trim())){ File newFile = new File(filename); FileOutputStream os = new FileOutputStream(newFile); os.write(file.getBytes()); os.close(); file.transferTo(newFile); //上傳到OSS uploadUrl = aliyunOSSUtil.upload(newFile); System.out.println(uploadUrl); model.addAttribute("file",uploadUrl); } } }catch (Exception ex){ ex.printStackTrace(); } return "forward:getAllPic"; } }
到此這篇關(guān)于springboot+thymeleaf整合阿里云OOS對象存儲圖片的實現(xiàn)的文章就介紹到這了,更多相關(guān)springboot+thymeleaf對象存儲圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Springboot詳解如何整合使用Thymeleaf
- springboot整合shiro之thymeleaf使用shiro標(biāo)簽的方法
- SpringBoot整合thymeleaf 報錯的解決方案
- SpringBoot使用thymeleaf實現(xiàn)一個前端表格方法詳解
- Springboot使用thymeleaf動態(tài)模板實現(xiàn)刷新
- 淺析SpringBoot中使用thymeleaf找不到.HTML文件的原因
- springboot如何使用thymeleaf模板訪問html頁面
- springboot中thymeleaf模板使用詳解
- SpringBoot?整合Thymeleaf教程及使用方法
相關(guān)文章
SpringBoot 項目添加 MDC 日志鏈路追蹤的執(zhí)行流程
日志鏈路追蹤就是將一個標(biāo)志跨線程進(jìn)行傳遞,在一般的小項目中也就是在你新起一個線程的時候,或者使用線程池執(zhí)行任務(wù)的時候會用到,比如追蹤一個用戶請求的完整執(zhí)行流程,本文給大家介紹SpringBoot MDC 日志鏈路追蹤的代碼,感興趣的朋友一起看看吧2021-06-06Java調(diào)用微信客服消息實現(xiàn)發(fā)貨通知的方法詳解
這篇文章主要介紹了Java調(diào)用微信客服消息實現(xiàn)發(fā)貨通知的方法,結(jié)合實例形式詳細(xì)分析了java針對微信接口調(diào)用的原理、調(diào)用方法與相關(guān)注意事項,需要的朋友可以參考下2017-08-08spring?mybatis環(huán)境常量與枚舉轉(zhuǎn)換示例詳解
這篇文章主要為大家介紹了spring?mybatis環(huán)境常量與枚舉轉(zhuǎn)換示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06RocketMQ4.5.X 實現(xiàn)修改生產(chǎn)者消費者日志保存路徑
這篇文章主要介紹了RocketMQ4.5.X 實現(xiàn)修改生產(chǎn)者消費者日志保存路徑方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07Spring MVC參數(shù)校驗詳解(關(guān)于`@RequestBody`返回`400`)
這篇文章主要介紹了Spring MVC參數(shù)校驗的相關(guān)資料,主要是針對`@RequestBody`返回`400`的問題,文中通過示例代碼介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面跟著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08