今天再进行创建项目时想使用阿里云oos进行存储图片 下面进行实操
1.先引入pom依赖
1 2 3 4 5 |
< dependency > < groupId >com.aliyun.oss</ groupId > < artifactId >aliyun-sdk-oss</ artifactId > < version >3.9.1</ version > </ dependency > |
2.编写前端thymleeaf代码tetsfile.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!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个参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
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相关密钥 * aliyun.oss.secret=eF0相关密钥 * 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 { //容器不存在,就创建 if (!ossClient.doesBucketExist(bucketName)) { ossClient.createBucket(bucketName); CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName); createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead); ossClient.createBucket(createBucketRequest); } //创建文件路径 String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace( "-" , "" ) + "-" + file.getName()); //上传文件 PutObjectResult result = ossClient.putObject( new PutObjectRequest(bucketName, fileUrl, file)); //设置权限 这里是公开读 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 { //关闭 ossClient.shutdown(); } return null ; }
/** * @desc 查看文件列表 */ public List<OSSObjectSummary> getObjectList() { OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); // 设置最大个数。 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); // 设置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 { // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 删除文件。 ossClient.deleteObject(bucketName, objectName); // 关闭OSSClient。 ossClient.shutdown(); } catch (Exception e) { e.printStackTrace(); } } } |
4.controller层编写
写到代码中取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
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 -> { // 这个将自己上传图片得地址复制到这里来 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" ; }
} |
到此这篇关于springboot+thymeleaf整合阿里云OOS对象存储图片的实现的文章就介绍到这了,更多相关springboot+thymeleaf对象存储图片内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://blog.csdn.net/m0_46607044/article/details/124631678
查看更多关于springboot+thymeleaf整合阿里云OOS对象存储图片的实现的详细内容...